Tutorialspoint.dev

Sets in JavaScript

In this article we would be discussing Set object provided by ES6. A set is a collection of items which 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 types of values 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 new set created is empty.

Returns:
A new set object

Now lets create some sets:
Example:

// 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.prototype.size
– It returns the number of elements in the Set.

Methods:



  1. Set.prototype.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.
    
    Returns: 
    The set object
    

    Example:

    // using Set.prototype.add(value)
    // creating an empty set
    var set1 = new Set();
      
    // set contains 10, 20
    set1.add(10);
    set1.add(20);
      
    // As this method returns
    // the set object hence chanining 
    // of add method can be done.
    set1.add(30).add(40).add(50);
      
    // prints 10, 20, 30, 40, 50
    console.log(set1);

  2. Set.prototype.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.
    
    Returns: 
    true if the value is succesfully deleted from the set else returns false.
    

    Example:

    // using Set.protoype.delete(value)
    // creating set it contains
    // f, o , d, i, e
    var set1 = new Set("foooodiiiieee");
      
    // deleting e from the set
    // it prints true
    console.log(set1.delete('e'));
      
    // set contains f, o, d, i
    console.log(set1);
      
    // deleting an element which is 
    // not in the set
    // prints false
    console.log(set1.delete('g'));

  3. Set.prototype.clear() – It removes all the element from the set.
    Syntax:

    set1.clear();
    
    Parameter:
    No parameters
    
    Returns: 
    undefined
    

    Example:

    // Using Set.prototype.clear()
    // creating a set 
    var set2 = new Set([10, 20, 30, 40, 50]);
      
    // prints {10, 20, 30, 40, 50}
    console.log(set2);
      
    // clearing set2
    set2.clear()
      
    // prints {}
    console.log(set2);

  4. Set.prototype.entries() – It returns an iterator object which contains an array having the entries of the set, in the insertion order.
    Syntax:

    set1.entries();
    
    Parameter:
    No parameters
    
    Returns: 
    It returns an iterator object that contains an
    array of [value, value] for every 
    element of the set, in the insertion order. 
    

    Example

    // Using Set.prototype.entries()
    // creating set 
    var set1 = new Set();
      
    // adding element to the 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]
    // prints [50, 50]
    console.log(getEntriesArry.next().value);
      
    // prints [30, 30]
    console.log(getEntriesArry.next().value);
      
    // prints [40, 40]
    console.log(getEntriesArry.next().value);

  5. Set.prototype.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
    
    Returns: 
    True if the value is present else it returns false.
    

    Example:



    // Using Set.prototype.has()
    // creating set 
    var set1 = new Set();
      
    // adding element to the set
    set1.add(50);
    set1.add(30);
                  
    // prints true
    console.log(set1.has(50));
      
    // prints false
    console.log(set1.has(10));

  6. Set.prototype.values() – It returns all the values from the Set in the same insertion order.
    Syntax:

    set1.values();
    
    Parameter:
    No parameters
    
    Returns: 
    An iterator object that contains all the values of the set in the same order 
    as they are inserted. 
    
  7. Set.prototype.keys() – It also returns all the values from the Set in the insertion order.
    Note: – It is similar to the values() in case of Sets
    Syntax:

    set1.keys();
    
    Parameter:
    No parameters
    
    Returns: 
    An iterator object that contains all the 
    values of the set in the same order
    as they are inserted. 
    

    Example:

    // Using Set.prototype.values()
    // Using Set.prototype.keys()
    // creating set 
    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();
      
    // prints a SetIterator
    // that contains {50, 30, 40, "Geeks", "GFG"}
    console.log(getValues);
      
    // getting all the values
    var getKeys = set1.keys();
      
    // prints a SetIterator
    // that contains {50, 30, 40, "Geeks", "GFG"}
    console.log(getKeys);

  8. Set.prototype.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 which is to be executed for each element of the Set.
    thisargument - Value to be used as this when executing callback.
    
    Returns: 
    Undefined
    

    The callback function is provided with three parameters as follows:

    • the element key
    • the element value
    • the Set object to be traversed

    Example:

    // Using Set.prototype.forEach(callback[, thisarg])
    // creating set 
    var set1 = new Set();
      
    // adding element to the set
    set1.add({Firstname: "Sumit", Lastname: "Ghosh"});
    set1.add(50);
    set1.add(30);
    set1.add(40);
    set1.add("Geeks");
    set1.add("GFG");
      
    // Declaring a call back function
    // we are using only one parameter value
    // so it will ignore other two .
    function printOne(values)
    {
        console.log(values);
    }
      
    // It prints value of all the element 
    // of the set
    set1.forEach(printOne);
      
    // Declaring a call back function
    // we are using two parameter value
    // so it will ignore last one 
    function printTwo(key, values)
    {
        console.log(key+"  "+values);
    }
      
    // As key and values are same in set
    // so it will print values twice
    set1.forEach(printTwo);
      
    // Declaring a call back function
    // we are using all three paramter value
    function printThree(key, values, set)
    {
        // it will print key and value 
        // and the set object
                      
        console.log(key+"  "+values);
        console.log(set);
    }
      
    // It prints key and value of each 
    // element and the entire set object
    set1.forEach(printThree);

    Note:- In the above example we use a simple callback function which just print an element in the console, it can be designed to perform any complex operation as per requirement

  9. Set.protoype[@@iterator]() – It returns a Set iterator function which is values() function by default.
    Syntax:

    set1[Symbol.iterator]();
    
    Parameter:
    No parameters
    
    Returns: 
    A Set iterator function and it is values() by default.

    Example:

    // using Set.protoype[@@Iterator]()
    var set1 = new Set(["sumit","sumit","amit","anish"]);
      
    var getit = set1[Symbol.iterator]();
      
    // Printing the values in the 
    // iterator "getit" 
      
    // prints {value: "sumit", done: false}
    console.log(getit.next());
      
    // prints {value: "amit", done: false}
    console.log(getit.next());
      
    // prints {value: "anish", done: false}
    console.log(getit.next());
      
    // prints {value: undefined, done: true}
    console.log(getit.next());

Set Operations:

  1. subSet() – 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:



    // check whether the set on which the 
    // method is invoked is the subset of 
    // otherset or not
    Set.prototype.subSet = function(otherSet)
    {
        // if size of this set is greater
        // than otherSet then it can'nt 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));

  2. union() – It returns a Set which consists of union of Set A and Set B
    A Set is said to be a union of two set, if it contains all element of Set A as well as all elements of Set B, but it does’nt contains duplicate elements.
    For Example: If an element is present in both Set A and Set B then union of Set A and B will contain the single copy of the element.
    Let implement and use the union function
    Example:

    // Perform union operation between 
    // called set and otherSet
    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);
      
    // prints [10, 20, 30, 40, 50, 60, 70, 80]
    console.log(unionSet.values());

  3. intersection() – 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 element which is present both in Set A and Set B.
    Let implement and use the intersection function
    Example:

    // Performs intersection operation between
    // called set and otherSet
    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);
      
    // prints {40, 50}
    console.log(intersectionSet.values());

  4. difference() – It returns the Set which contains difference of Set A and Set B.
    A Set is said to be a difference of Set A and B if it contains set of element e which are present in Set A but not in Set B.
    Let’s implement and use the difference function
    Example:

    // Performs difference operation between
    // called set and otherSet
    Set.prototype.difference = function(otherSet)
    {
        // creating new set to store differnce
         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);
      
    // prints {10, 20, 30}
    console.log(differenceSet);

Reference:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter