Skip to content
Related Articles
Open in App
Not now

Related Articles

Sets in JavaScript

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 12 Jan, 2023
Improve Article
Save Article

In this article, we would be discussing the Set object provided by ES6. A set is a collection of items that are unique i.e no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. Set can store any type of value whether primitive or objects.

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.

Returns: A new set object

Example:  

Javascript




// it contains
// ["sumit","amit","anil","anish"]
var set1 = new Set(["sumit","sumit","amit","anil","anish"]);
  
// it contains 'f', 'o', 'd'
var set2 = new Set("fooooooood");
  
// it contains [10, 20, 30, 40]
var set3 = new Set([10, 20, 30, 30, 40, 40]);
  
 // it is an  empty set
var set4 = new Set();


Properties: 

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

Methods of Set: 

Set.add() – It 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: 

Javascript




var 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}

Set.delete() – It 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: 

Javascript




var 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

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

Syntax: 

set1.clear();

Parameter: This method does not take any parameter

Return value: Undefined

Example: 

Javascript




var 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}

Set.entries() – It 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:

Javascript




var set1 = new Set();
  
set1.add(50);
set1.add(30);
set1.add(40);
set1.add(20);
set1.add(10);
  
// using entries to get iterator
var 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]

Set.has() – It 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: 

Javascript




var 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

Set.values() – It 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. 

Set.keys(): It 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

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

Example: 

Javascript




var 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
var getValues = set1.values();
  
console.log(getValues);
  
var getKeys = set1.keys();
  
console.log(getKeys);


Output:

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

Set.forEach(): It 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

Set.prototype[@@iterator](): It 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: 

Javascript




var set1 = new Set(["sumit","sumit","amit","anish"]);
  
var 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:  

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: 

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(var 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
var setA = new Set([10, 20, 30]);
var setB = new Set([50, 60, 10, 20, 30, 40]);
var 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: 

Javascript




Set.prototype.union = function(otherSet)
{
    // creating new set to store union
    var unionSet = new Set();
  
    // iterate over the values and add 
    // it to unionSet
    for (var elem of this)
    {
        unionSet.add(elem);
    }
  
    // iterate over the values and add it to 
    // the unionSet
    for(var elem of otherSet)
        unionSet.add(elem);
  
    // return the values of unionSet
    return unionSet;
}
  
// using the union function
// Declaring values for set1 and set2
var set1 = new Set([10, 20, 30, 40, 50]);
var set2 = new Set([40, 50, 60, 70, 80]);  
  
// performing union operation
// and storing the resultant set in 
// unionSet
var 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:  

Javascript




Set.prototype.intersection = function(otherSet)
{
    // creating new set to store intersection
    var intersectionSet = new Set();
  
    // Iterate over the values 
    for(var 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
var set1 = new Set([10, 20, 30, 40, 50]);
var set2 = new Set([40, 50, 60, 70, 80]);  
  
// performing union operation
// and storing the resultant set in 
// intersectionset
var 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:  

Javascript




Set.prototype.difference = function(otherSet)
{
    // creating new set to store difference
     var differenceSet = new Set();
  
    // iterate over the values
    for(var 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
var set1 = new Set([10, 20, 30, 40, 50]);
var set2 = new Set([40, 50, 60, 70, 80]);  
  
// performing union operation
// and storing the resultant set in 
// intersectionset
var 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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!