Get the Intersection of two Sets using JavaScript


Borislav Hadzhiev

Fri Oct 29 20212 min read

Get the Intersection of two Sets #

To get the intersection of two Sets:

  1. Convert the first Set into an array.
  2. Use the filter() method to iterate over the array.
  3. Use the has() method to check if each value is contained in the second Set.
  4. Convert the array back to a Set.
function getIntersection(setA, setB) { const intersection = new Set( [...setA].filter(element => setB.has(element)) ); return intersection; } const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd', 'e']); console.log(getIntersection(set1, set2)); // 👉️ {'a', 'b'}

We used the spread syntax (...) to convert the first Set into an array, so we can call the Array.filter method on it.

console.log([...set1]); // 👉️ ['a', 'b', 'c']

The function we passed to the filter method gets called with each element in the array.

If the function returns a truthy value, the element is included in the new array that the filter method returns.

On each iteration, we call the Set.has method to check if the value is contained in the second Set.

The has() method returns true if the value is found in the Set, and false otherwise.

The array that the filter method returns contains only the values that are found in both Set objects, in other words, the intersection.

The last step is to convert the array back into a Set, using the Set() constructor.

The Set() constructor takes an iterable object, such as an array, and adds all of its values into a newly created Set.

Finding the intersection of two Sets is quite straight forward because Sets contain no duplicate values.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.