Get the Intersection of two Sets using JavaScript


Borislav Hadzhiev

Last updated: Jul 24, 2022


Photo from Unsplash

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 to an array, on which we can call the Array.filter method.

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 use the Set() constructor to convert the array back to a Set.

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 Set objects contain no duplicate values.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.