Open In App

What is Set Intersection in JavaScript ?

In JavaScript, the concept of Set intersection refers to finding the common elements between two or more sets. The result of the intersection operation is a new Set containing only the elements that are common to all the input sets.

Example: Here, The spread operator ([...set1]) is used to convert the elements of set1 into an array. The filter() method is applied to the array, retaining only the elements that are present in set2 using the has() method.




const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([3, 4, 5, 6]);
 
// Find the intersection of set1 and set2
const intersection = new Set([...set1]
    .filter(element => set2.has(element)));
 
console.log(intersection); // Output: Set { 3, 4 }

Output
Set(2) { 3, 4 }

Article Tags :