How to Get the Symmetric Difference of Two JavaScript Sets?

In mathematical terms, the symmetrical difference of two sets is expressed as A △ B or A ⊖ B (i.e. set of all uncommon elements between "A" and "B"). It is basically the opposite of intersection.

To get the symmetric difference of two JavaScript Set objects, you can:

  1. Create a copy of one of the existing sets;
  2. Loop over the other set, and check if the current value exists in the copy set:
    • If it does, then remove the common value from the copy set;
    • If it doesn't, then add the value to the copy set.

For example:

function symmetricDifference(setA, setB) {
    const diff = new Set(setA);

    for (const elem of setB) {
        const operation = (diff.has(elem)) ? 'delete' : 'add';
        diff[operation](elem);
    }

    return diff;
}

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

console.log(symmetricDifference(setA, setB)); // Set(4) {1, 2, 5, 6}

The ternary inside the loop is meant as a shorthand for if/else. You can replace it with if/else if you want.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.