What is  Set  in JavaScript?

What is Set in JavaScript?

Set

The Set is a collection is dissimilar elements and we can say, it stores the unique element. Set is an object in JavaScript.

We can create a set by just writing Set(). It will create a new set.

Or we can create a non-empty set like ---> const setA = new Set([1 ,2 ,3 ,4 , 5]);

Methods in a Set

Add method --> This method is used to add new elements to an existing set.

let setOfElements = new Set()

setOfElements.add(2);
setOfElements.add(3);
setOfElements.add(4);
setOfElements.add(5);
console.log(setOfElements);

Size Method-> This method is used to find out the size of a set or we say how many elements are present in a set.


let setOfElements = new Set()
//Add an element
setOfElements.add(2);
setOfElements.add(3);
setOfElements.add(4);
setOfElements.add(5);
console.log(setOfElements);

// Finding the size of the element..

console.log(setOfElements.size);

Clear() method --> this method removes all the elements from a set object.

// Clear method
setOfElements.clear();
console.log(setOfElements);

delete method() --> The delete() method removes a specified value from a Set object, if it is in the set. It will return true if the element is successfully removed or else prints false.

const mySet = new Set();
mySet.add("foo");

console.log(mySet.delete("bar")); // false; no "bar" element found to be deleted.
console.log(mySet.delete("foo")); // true; successfully removed.

console.log(mySet.has("foo")); // false; the "foo" element is no longer present.

has method() --> This method is used to check whether the element is present in a set or not. It will provide boolean results, it will print true if it is present in a set or if not it will print false.

let setOfElements = new Set()
setOfElements.add(2);
setOfElements.add(3);
setOfElements.add(4);
setOfElements.add(5);
console.log(setOfElements.has(3));
// It will print result true
 console.log(setOfElements.has(34));
// It will print result false

values() method --> The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.

const set1 = new Set();
set1.add(42);
set1.add('forty two');

const iterator1 = set1.values();

console.log(iterator1.next().value);
// Expected output: 42

console.log(iterator1.next().value);
// Expected output: "forty two"

intersection() and difference() method ---> The intersection() method is used for finding the intersection between the two sets or we can say that we get the common element from two or more sets.

The difference() method used is for finding the difference between the two sets. Let us take an example, suppose we have setA and SetB,

SetA = {1, 2, 3, 4} , SetB = {1,5,6,7}.

The difference between setA - SetB is {2,3,4};

Let us illustrate this method with the help of source code ----->

//converting between Set and Array
const mySet1 = new Set([1, 5, 6,7]);
const mySet2 = new Set([1, 2, 3, 4]);
// console.log(mySet2.size); // 4
// console.log([...mySet2]); // [1, 2, 3, 4]

// intersect can be simulated via
// filter() method is used for filtering the desired value
// has() checks whether the value is present in it or not.
const intersection = new Set([...mySet1].filter((x) => mySet2.has(x)));
console.log(intersection);
// set(1) {1}

// difference can be simulated via
const difference = new Set([...mySet1].filter((x) => !mySet2.has(x)));
console.log(difference);
//set(3){5,6,7}
// Iterate set entries with forEach()
mySet2.forEach((value) => {
  console.log(value);
});
// 1
// 2
// 3

Set Operations

Check Whether A is a subset of B

// Check whether A is a superset of B ....
const setA = new Set([1,2,3,4]);
const setB = new Set([1,2,5]);


function CheckSuperSet(setA,setB){

 for(const elem of setB){
    if(!setA.has(elem)){
    return false;
    }  
}
return true;
}

console.log(CheckSuperSet(setA,setB));

Finding Union of two sets

// Finding union of two sets
// 1st method

function findUnion(setA,setB){
    const setC = new Set();
    for(elem of setA){
        setC.add(elem)
    }
    for(elem of setB){
        setC.add(elem)
    }

    return setC;
}

//  2st method
function findUnion(setA,setB){
    const setC = new Set(setA);
    for(elem of setB){
        setC.add(elem)
    }

    return setC;
}
console.log(findUnion(setA,setB));

Finding an intersection between two sets

function findIntersection(setA,setB){
    const interSectElement = new Set();     
      for(elem of setB){
        if(setA.has(elem)){
            interSectElement.add(elem);
          }

        }
        return interSectElement;

    }

console.log(findIntersection(setA,setB));

Finding an difference between two sets

//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// Finding difference  between two sets
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------

function findDiffrerence(setA,setB){
    const interSectElement = new Set(setA);     
      for(elem of setB){

        if(setA.has(elem)){
            interSectElement.delete(elem);
          }

        }
        return interSectElement;

    }

console.log(findDiffrerence(setA,setB));

For more resources check the below link.

Thanks for reading my blog, have a wonderful day.