How to get the difference between two sets in JavaScript

Last updated on November 06, 2023
How to get the difference between two sets in JavaScript

Get asymmetric difference between two sets

To get the difference between two sets in JavaScript, use the Array filter() and Set has() methods like this:

function getDifference(setA, setB) {
  return new Set(
    [...setA].filter(element => !setB.has(element))
  );
}

const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([2, 4]);

console.log(getDifference(set1, set2)); // {1, 3}

The Set has() method returns true if the Set contains a particular element and returns false if it doesn't.

const arr = ['a', 'b', 'c'];

const set = new Set(arr);

console.log(set.has('a')); // true

Array filter() runs a callback on every element of an array and returns an array of elements that the callback returns true for.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter(
  (number) => number % 2 === 0
);

console.log(evenNumbers); // [2, 4, 6, 8, 10]

The spread syntax (...) converts the set to an array for filter() to work.

The Set() constructor converts the result of filter() back to an Set.

Get symmetric difference between two sets

The method above only gives the elements in the second set that aren't in the first.

function getDifference(setA, setB) {
  return new Set(
    [...setA].filter((element) => !setB.has(element))
  );
}

const set1 = new Set([2, 4]);
const set2 = new Set([1, 2, 3, 4]);

// Every item in set1 is also in set2, but the sets are different
console.log(getDifference(set1, set2)); // {}

Sometimes you want this, especially if set2 is supposed to be a set1's subset.

But other times you may want to find the symmetric difference between the sets, regardless of which one comes first.

To do that, we simply merge the results of two getDifference() calls, each with the order of the Sets reversed.

function getDifference(setA, setB) {
  return new Set(
    [...setA].filter((element) => !setB.has(element))
  );
}

function getSymmetricDifference(setA, setB) {
  return new Set([
    ...getDifference(setA, setB),
    ...getDifference(setB, setA),
  ]);
}

const set1 = new Set([2, 4]);
const set2 = new Set([1, 2, 3, 4]);

console.log(getSymmetricDifference(set1, set2)); // {1, 3}
console.log(getSymmetricDifference(set2, set1)); // {1, 3}

See also