Get the Intersection of two Sets using JavaScript

Borislav Hadzhiev

Fri Oct 29 2021ยท2 min read

Photo by Vladimir Fedotov

**To get the intersection of two Sets:**

- Convert the first
`Set`

into an array. - Use the
`filter()`

method to iterate over the array. - Use the
`has()`

method to check if each value is contained in the second`Set`

. - Convert the array back to a
`Set`

.

index.js

Copied!`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.

index.js

Copied!`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.

I'll send you 1 email a week with links to all of the articles I've written that week