Borislav Hadzhiev
Fri Oct 29 2021·2 min read
Photo by Antoine Therizols
To get the difference between two Sets:
Set
to an Array.filter()
method to iterate over the array.has()
method to check if each element is not contained in the
second Set
.Set
.function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b']); console.log(getDifference(set1, set2)); // 👉️ {'c'}
We used the
spread syntax (...)
to convert the first Set
to an array, so we can call the
Array.filter
method on it.
The function we passed to the filter
method gets called with each element in
the array.
filter
method returns a new array containing the elements, for which the callback function returns a truthy value.On each iteration, we check if the element is not contained in the second Set
by negating the result from the
Set.has()
method.
The has()
method returns true
if the element is contained in the Set
, and
false
otherwise.
Set
are not contained in the second Set
. We didn't check if the elements from the second Set
are not contained in the first.function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set(['a']); const set2 = new Set(['a', 'b', 'c']); console.log(getDifference(set1, set2)); // 👉️ {}
In the example above, we got an empty Set
for the difference, where a Set
containing {'b', 'c'}
would have been expected.
We only iterated over the first Set
, which has 1
element, so we didn't get
the complete difference.
getDifference
method two times and combine the results.function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set(['a']); const set2 = new Set(['a', 'b', 'c']); const difference = new Set([ ...getDifference(set1, set2), ...getDifference(set2, set1), ]); console.log(difference); // 👉️ {'b', 'c'}
Here's what we did to get this working:
Set
and return only the elements
that are not contained in the second Set
.Set
and return only the elements
that are not contained in the first.Set
.Now, our example contains the complete difference between the two Set
objects.