Open In App

How to perform intersection of two sets in JavaScript ?

Last Updated : 07 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 of two sets in many ways:

  • JavaScript Sets: Set can store any type of value whether primitive or objects.
  • JavaScript filter() Method: Create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. 
  • JavaScript set.has() Method: Check whether an element with a specified value exists in a Set or not.

Using Sets & has() Method: 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. A set can store any type of value whether primitive or objects.

Example 1: In this example, we will see the intersection of sets by using the set.has() method.

Javascript




function getIntersection(set1, set2) {
    const ans = new Set();
    for (let i of set2) {
        if (set1.has(i)) {
            ans.add(i);
        }
    }
    return ans;
}
const set1 = new Set([1, 2, 3, 8, 11]);
const set2 = new Set([1, 2, 5, 8]);
  
const result = getIntersection(set1, set2);
console.log(result);


Output:

Set(3) { 1, 2, 8 }

Using the has() & filter() Method: We check if the element is present in set1 also then we are going to add that element to the new set. 

Example 2: In this example, we will see the intersection of sets by using the filter() method. We have also used the spread operator for separating the element.

Javascript




let set1 = new Set([1, 2, 3]);
let set2 = new Set([4, 3, 2]);
let set = new Set([...set1].filter(x => set2.has(x)));
console.log(set);


Output:

Set(2) { 2, 3 }


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads