The Wayback Machine - https://web.archive.org/web/20241001043551/https://www.geeksforgeeks.org/sets-in-javascript/
Open In App

Sets in JavaScript

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Sets in JavaScript are collections of unique values, meaning no duplicates are allowed. They provide efficient ways to store and manage distinct elements. Sets support operations like adding, deleting, and checking the presence of items, enhancing performance for tasks requiring uniqueness.

Syntax: 

new Set([it]);

Parameter: 

  • it: It is an iterable object whose all elements are added to the new set created, If the parameter is not specified or null is passed then a new set created is empty.

Return Value:

A new set object.

Example: This example shows the implementation of a JavaScript set.

JavaScript
// ["sumit","amit","anil","anish"]
let set1 = new Set(["sumit","sumit","amit","anil","anish"]);

// it contains 'f', 'o', 'd'
let set2 = new Set("fooooooood");

// it contains [10, 20, 30, 40]
let set3 = new Set([10, 20, 30, 30, 40, 40]);

 // it is an  empty set
let set4 = new Set();


Properties of Set in JavaScript: 

Set.size – It returns the number of elements in the Set.

Methods of Set in JavaScript: 

1. Set.add()

Set.add() adds the new element with a specified value at the end of the Set object.

Syntax: 

set1.add(val);

Parameter:

  • val: It is a value to be added to the set.

Return value: The set object

Example: In this example, we are adding values into the set by using add() method.

JavaScript
let set1 = new Set();

set1.add(10);
set1.add(20);

// As this method returns
// the set object hence chaining 
// of add method can be done.
set1.add(30).add(40).add(50);

console.log(set1);

Output:

Set(5) {10, 20, 30, 40, 50}

2. Set.delete()

Set.delete() deletes an element with the specified value from the Set object. 

Syntax: 

set1.delete(val);

Parameter:

  • val: It is a value to be deleted from the set.

Return value: true if the value is successfully deleted from the set else returns false.

Example: In this example, we are deleting the values into the set by using delete() method.

JavaScript
let set1 = new Set("foooodiiiieee");

// deleting e from the set
// it prints true
console.log(set1.delete('e'));

console.log(set1);

// deleting an element which is 
// not in the set
// prints false
console.log(set1.delete('g'));

Output:

true
Set(4) {'f', 'o', 'd', 'i'}
false

3. Set.clear()

Set.clear() removes all the element from the set. 

Syntax: 

set1.clear();

Parameter:

This method does not take any parameter

Return value: Undefined

Example: In this example, we are clearing the values into the set by using clear() method.

JavaScript
let set2 = new Set([10, 20, 30, 40, 50]);

console.log(set2);

set2.clear()

console.log(set2);

Output:

Set(5) {10, 20, 30, 40, 50}
Set(0) {size: 0}

4. Set.entries()

Set.entries() returns an iterator object which contains an array having the entries of the set, in the insertion order. 

Syntax:

set1.entries();

Parameter:

This method does not take any parameter

Return value: It returns an iterator object that contains an array of [value, value] for every element of the set, in the insertion order. 

Example: In this example, we are using enteries() method.

JavaScript
let set1 = new Set();

set1.add(50);
set1.add(30);
set1.add(40);
set1.add(20);
set1.add(10);

// using entries to get iterator
let getEntriesArry = set1.entries();

// each iterator is array of [value, value]
console.log(getEntriesArry.next().value);

console.log(getEntriesArry.next().value);

console.log(getEntriesArry.next().value);

Output:

(2) [50, 50]
(2) [30, 30]
(2) [40, 40]

5. Set.has()

Set.has() returns true if the specified value is present in the Set object. 

Syntax:  

set1.has(val);

Parameter: 

  • val: The value to be searched in the Set

Return value: True if the value is present else it returns false.

Example: In this example, we are checking whether the value is present in the set by using has() method.

JavaScript
let set1 = new Set();

// adding element to the set
set1.add(50);
set1.add(30);
            
console.log(set1.has(50));

console.log(set1.has(10));

Output:

true
false

6. Set.values()

Set.values() returns all the values from the Set in the same insertion order. 

Syntax:  

set1.values();

Parameter:

This method does not take any parameter

Return value: An iterator object that contains all the values of the set in the same order as they are inserted.

7. Set.keys()

Set.keys() also returns all the values from the Set in the insertion order. 

Note: It is similar to the values() in the case of Sets 

Syntax: 

set1.keys();

Parameter:

This method does not take any parameter

Return Value: An iterator object that contains all the values of the set in the same order as they are inserted. 

Example: In this example, we are printing all the values of the set by using keys() method.

JavaScript
let set1 = new Set();

// adding element to the set
set1.add(50);
set1.add(30);
set1.add(40);
set1.add("Geeks");
set1.add("GFG");

// getting all the values
let getValues = set1.values();

console.log(getValues);

let getKeys = set1.keys();

console.log(getKeys);

Output:

SetIterator {50, 30, 40, 'Geeks', 'GFG'}
SetIterator {50, 30, 40, 'Geeks', 'GFG'}

8. Set.forEach()

Set.forEach() executes the given function once for every element in the Set, in the insertion order. 

Syntax:  

set1.forEach(callback[,thisargument]);

Parameter:

  • callback – It is a function that is to be executed for each element of the Set.
    • The callback function is provided with three parameters as follows: 
      • the element key
      • the element value
      • the Set object to be traversed
  • thisargument – Value to be used as this when executing the callback.

Return value: Undefined

9. Set.prototype[@@iterator]()

Set.prototype[@@iterator]() returns a Set iterator function which is values() function by default. 

Syntax: 

set1[Symbol.iterator]();

Parameter:

This method does not take any parameter

Return value:   A Set iterator function and it is values() by default.

Example: In this example, we are iterating the values from the set.

JavaScript
let set1 = new Set(["sumit","sumit","amit","anish"]);

let getit = set1[Symbol.iterator]();

console.log(getit.next());

console.log(getit.next());

console.log(getit.next());

console.log(getit.next());

Output:

{value: 'sumit', done: false}
{value: 'amit', done: false}
{value: 'anish', done: false}
{value: undefined, done: true}

Set Operations in JavaScript

JavaScript subSet() Method:

It returns true if Set A is a subset of Set B.  A Set A is said to be a subset of Set B, if all the elements of Set A is also present in Set B. Now lets implement and use the subset function. 

Example: In this example, we are checking whether the given subset is present in the given set or not and returning the result according to it.

JavaScript
Set.prototype.subSet = function(otherSet)
{
    // if size of this set is greater
    // than otherSet then it can't be 
    //  a subset
    if(this.size > otherSet.size)
        return false;
    else
    {
        for(let elem of this)
        {
            // if any of the element of 
            // this is not present in the
            // otherset then return false
            if(!otherSet.has(elem))
                return false;
        }
        return true;
    }
}

// using the subSet function

// Declaring different sets
let setA = new Set([10, 20, 30]);
let setB = new Set([50, 60, 10, 20, 30, 40]);
let setC = new Set([10, 30, 40, 50]);

// prints true
console.log(setA.subSet(setB));

// prints false
console.log(setA.subSet(setC));

// prints true
console.log(setC.subSet(setB));

Output:

true
false
true

JavaScript union() Method:

It returns a Set which consists of the union of Set A and Set B. A Set is said to be a union of two sets, if it contains all elements of Set A as well as all elements of Set B, but it doesn’t contain duplicate elements. 

If an element is present in both Set A and Set B then the union of Set A and B will contain a single copy of the element. Let’s implement and use the union function 

Example: In this example, we are merging the two sets.

JavaScript
Set.prototype.union = function(otherSet)
{
    // creating new set to store union
    let unionSet = new Set();

    // iterate over the values and add 
    // it to unionSet
    for (let elem of this)
    {
        unionSet.add(elem);
    }

    // iterate over the values and add it to 
    // the unionSet
    for(let elem of otherSet)
        unionSet.add(elem);

    // return the values of unionSet
    return unionSet;
}

// using the union function
// Declaring values for set1 and set2
let set1 = new Set([10, 20, 30, 40, 50]);
let set2 = new Set([40, 50, 60, 70, 80]);  

// performing union operation
// and storing the resultant set in 
// unionSet
let unionSet = set1.union(set2);

console.log(unionSet.values());

Output:

SetIterator {10, 20, 30, 40, 50, …}

JavaScript intersection() Method:

It returns the intersection of Set A and Set B. A Set is said to be the intersection of Set A and B if contains an element which is present both in Set A and Set B. Let’s implement and use the intersection function 

Example: In this example, we are finding the insersection of two sets.

JavaScript
Set.prototype.intersection = function(otherSet)
{
    // creating new set to store intersection
    let intersectionSet = new Set();

    // Iterate over the values 
    for(let elem of otherSet)
    {
        // if the other set contains a 
        // similar value as of value[i]
        // then add it to intersectionSet
        if(this.has(elem))
            intersectionSet.add(elem);
    }

// return values of intersectionSet
return intersectionSet;                
}
// using intersection function
// Declaring values for set1 and set2
let set1 = new Set([10, 20, 30, 40, 50]);
let set2 = new Set([40, 50, 60, 70, 80]);  

// performing union operation
// and storing the resultant set in 
// intersectionset
let intersectionSet = set1.intersection(set2);

console.log(intersectionSet.values());

Output:

SetIterator {40, 50}

JavaScript difference() Method:

It returns the Set which contains the difference between Set A and Set B. A Set is said to be a difference between Set A and B if it contains set of elements e which are present in Set A but not in Set B. Let’s implement and use the difference function 

Example: In this example, we are finding the difference of two sets. 

JavaScript
Set.prototype.difference = function(otherSet)
{
    // creating new set to store difference
    let differenceSet = new Set();

    // iterate over the values
    for(let elem of this)
    {
        // if the value[i] is not present 
        // in otherSet add to the differenceSet
        if(!otherSet.has(elem))
            differenceSet.add(elem);
    }

    // returns values of differenceSet
    return differenceSet;
}

// using difference function
// Declaring values for set1 and set2
let set1 = new Set([10, 20, 30, 40, 50]);
let set2 = new Set([40, 50, 60, 70, 80]);  

// performing union operation
// and storing the resultant set in 
// intersectionset
let differenceSet = set1.difference(set2);

console.log(differenceSet);

Output:

Set(3) {10, 20, 30}

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Sets in JavaScript – FAQs

What is a Set in JavaScript?

A Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references. Unlike arrays, Sets automatically ensure that no duplicate values are present.

How do you create a Set?

You can create a Set using the Set constructor: const mySet = new Set();

How do you add values to a Set?

You can add values to a Set using the add() method, which takes one argument, the value to be added: mySet.add(1);

How do you check if a value exists in a Set?

You can check if a value exists in a Set using the has() method, which returns true if the value is present, and false otherwise: mySet.has(1);

How do you remove a value from a Set?

You can remove a value from a Set using the delete() method, which takes one argument, the value to be removed: mySet.delete(1);

How do you clear all values from a Set?

You can remove all values from a Set using the clear() method: mySet.clear();

How do you get the size of a Set?

You can get the number of values in a Set using the size property: mySet.size;



Previous Article
Next Article

Similar Reads

How to perform intersection of two sets in JavaScript ?
An intersection of two sets means the element which occurs in both sets. In mathematical terms, the intersection of two sets is shown by A ∩ B. It means all the elements which is common in set A and set B should occur in a single array. In javascript, the intersection of two sets means getting the common from both sets. We can find the intersection
2 min read
How to get the union of two sets in JavaScript ?
A union set is the combination of two elements. In mathematical terms, the union of two sets is shown by A ∪ B. It means all the elements in set A and set B should occur in a single array. In JavaScript, a union set means adding one set element to the other set. Set automatically take care of the uniqueness of elements. Below are the approaches thr
2 min read
What is the use of Delete method in Sets in JavaScript ?
In JavaScript Sets, the delete() method is used to remove a specified element from the Set. It returns a boolean value indicating whether the element was successfully deleted. Syntax:mySet.delete(value);Parameters:mySet: The Set from which the element is to be deleted.value: The value of the element to be deleted from the Set.Example: Here, the del
1 min read
What is the use of the Clear method in Sets in JavaScript ?
The clear() method in JavaScript Sets is used to remove all elements from a Set, effectively making the Set empty. It does not take any arguments and does not return any value. After calling the clear(), the Set will have a size of 0. Example: Here, the clear() method is called on the mySet Set, removing all elements and leaving an empty Set. C/C++
1 min read
What is the use of the Add method in Sets in JavaScript ?
In JavaScript, the add() method is used with Sets to add a new element to the Set. It ensures that the element is unique within the Set, meaning that duplicates are automatically ignored. Example: Here, the add() method is used to add the values 1, 2, and 3 to the Set mySet. When the value 1 is added a second time, the Set automatically handles it,
1 min read
What is the use of the Values method in JavaScript Sets ?
In JavaScript Sets, the values() method is used to return a new iterator object that contains the values for each element in the Set, in insertion order. The iterator object follows the iterable protocol, allowing you to loop through the values using methods like next(). Syntax:mySet.values()mySet: The Set for which you want to obtain an iterator f
1 min read
JavaScript Program to Merge Two Sets
Given two sets, our task is to Merge Two Sets into a new set so that unique elements will be present in the new set from both sets. Example:Input:set1 = ([1, 2, 3, 4])set2 = ([3, 4, 5, 6])Output:Set(5) { 1, 2, 3,4, 5, 6} Explanation:The unique elements present in set are : 1, 2, 3, 4, 5, 6Below are the approaches to Merge Two Sets using JavaScript:
3 min read
Get the Difference between Two Sets using JavaScript
To get the difference between two sets in JavaScript, you need to identify elements present in the first set but not in the second. This involves iterating over the first set and filtering out elements that are also found in the second set, ensuring efficient comparison. We can get the difference between two sets using Javascript by the following m
2 min read
Javascript Program for Counting sets of 1s and 0s in a binary matrix
Given a n × m binary matrix, count the number of sets where a set can be formed one or more same values in a row or column. Examples: Input: 1 0 1 0 1 0 Output: 8 Explanation: There are six one-element sets (three 1s and three 0s). There are two two- element sets, the first one consists of the first and the third cells of the first row. The second
2 min read
How to iterate over three paragraphs and sets their color property red in jQuery ?
In this article, we will learn how to iterate over three paragraphs and sets their color property red in jQuery. We have three paragraphs, and we want to iterate on these paragraphs and set their color property to red. Approach: To do that, first, we add a button and on click this button, a function is called which name is fun() and in this functio
1 min read
One flex/grid item sets the size limit for siblings in CSS
When working with CSS Grid or Flexbox, it is possible to set a size limit for siblings using one item as a reference. This means that the size of all other siblings will be defined in relation to the reference item, creating a layout that is both flexible and consistent. Syntax: To set a size limit for siblings in CSS Grid or Flexbox, you can use t
2 min read
Which Property sets all Outline Properties at once in CSS?
The outline property in CSS sets all outline properties at once, allowing you to specify the color, style, and width of an element's outline. This consolidated property simplifies the process of styling outlines for better visual presentation and accessibility. Syntax:/* Setting all outline properties at once */.element { outline: 2px dashed #3498d
1 min read
Which Property Sets Outline Color in CSS?
The outline-color property in CSS is specifically used to set the colour of an element's outline. It allows you to define the visual appearance of the outline, providing flexibility in styling for better visual presentation and accessibility. Syntax:/* Setting a color of the outline in CSS */.element { outline-color: #e74c3c; /* Example color value
1 min read
How to find all divs with a name attribute that contains word 'geeks' and sets the background color ?
jQuery contains attribute selectors with the help of which we can select the elements with name attribute as a particular string or select the elements which contain a particular string or begin with a particular string or ends with a particular string or don't contain a particular string as a name attribute. In this article, we will learn to find
4 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important attribute of <script> tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. <script> cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &&:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
JavaScript Course Operators in JavaScript
An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithmetic operations, etc. There are various operators
7 min read
JavaScript Course Functions in JavaScript
Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it). Function Structure: To create a function, we use function() declaration. // Anonymous function function(){ // function...body } // function with a name function displayMessage(){
4 min read
JavaScript Course Conditional Operator in JavaScript
JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the code block inside it will be executed otherwise n
3 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
How can JavaScript codes be hidden from old browsers that do not support JavaScript ?
Nowadays all modern browsers support JavaScript, however, older browsers did not support JavaScript. In this article, we will learn how we can hide JavaScript code from running in older browsers. Approach: After opening the <script> tag, we will use a one-line HTML style comment without any closing character ( <!-- ). We will then write th
2 min read
How are the JavaScript window and JavaScript document different from one another?
What is a JavaScript window? The window is at a root/top level at the JavaScript object hierarchy. It is a global/root object in JavaScript and it is the root object of the Document object model(DOM); What is a JavaScript document? A document is an object inside the window object and we use a document object for manipulation inside the document. Th
3 min read
Explore the concept of JavaScript Function Scope and different types of JavaScript Functions
JavaScript is based on functional programming. Therefore, functions are fundamental building blocks of JavaScript. So the function is called first-class citizens in JavaScript. Syntax: Define a functionfunction functionName(parameters) { // SET OF STATEMENTS } Call a functionfunctionName(arguments); The function execution stops when all the stateme
10 min read
Which href value should we use for JavaScript links, "#" or "javascript:void(0)" ?
In this article, we will know which "href" should be used for JavaScript when we can use "#" or "javascript:void(0)". Let us understand it. Using the '#' value: The # is a fragment identifier used to refer to a specific section of the same document. When a user clicks a link with a # href, the browser will scroll to that section of the page specifi
3 min read
How to include a JavaScript file in another JavaScript file ?
In native JavaScript, before ES6 Modules 2015 was introduced had no import, include, or require functionalities. Before that, we can load a JavaScript file into another JavaScript file using a script tag inside the DOM that script will be downloaded and executed immediately. Now after the invention of ES6 modules, there are so many different approa
3 min read
JavaScript Program to find Length of Linked List using JavaScript
Given a linked list, the task is to determine its length using various methods. The linked list is a fundamental data structure consisting of nodes connected in a chain, offering efficient data organization. Different approaches, including Iterative and Recursive Methods, enable us to compute the length of a linked list easily. Use the below approa
3 min read
Practice Tags :