Borislav Hadzhiev
Fri Oct 29 2021·2 min read
Photo by Vladimir Fedotov
To get the intersection of two Sets:
Set
into an array.filter()
method to iterate over the array.has()
method to check if each value is contained in the second
Set
.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.
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
.