Last updated: Mar 3, 2024
Reading timeยท2 min

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 use the Array.filter() method.
The function we passed to the Array.filter() method gets called with each element in the array.
The filter() method returns a new array that only contains the elements that
meet the condition.
On each iteration, we check if the current element is not contained in the
second Set by negating the result of the
Set.has()
method.
function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); }
The has() method returns true if the element is contained in the Set, and
false otherwise.
However, this doesn't return the complete difference between the Set objects
because we only check if the elements of the first Set are not contained in
the second Set.
We didn't check if the elements of 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)); // ๐๏ธ {}

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.
To solve this issue, we need to call the 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.
You can learn more about the related topics by checking out the following tutorials: