Get the Difference between Two Sets using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

Get the Difference between Two Sets #

To get the difference between two Sets:

  1. Convert the first Set to an Array.
  2. Use the filter() method to iterate over the array.
  3. Use the has() method to check if each element is not contained in the second Set.
  4. Convert the array back to a Set.
index.js
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.

The 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.

However, this doesn't return the complete difference between the Sets, because we only check if the elements from the first 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.
index.js
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.

To solve this problem, we need to call the getDifference method two times and combine the results.
index.js
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:

  1. Iterate over the elements of the first Set and return only the elements that are not contained in the second Set.
  2. Iterate over the elements of the second Set and return only the elements that are not contained in the first.
  3. Combine the results into a third Set.

Now, our example contains the complete difference between the two Set objects.

Further Reading #

Join my newsletter

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

Buy Me A Coffee