How to Get the Difference of Two Sets in JavaScript?

One of the basic Set operations is to get the difference of two sets. In mathematical terms, this is expressed as A - B (i.e. set of all elements of "A" that are not elements of "B").

Please note that this is different than the symmetric difference of two sets (where you get all the uncommon elements between two sets).

To get a difference between two JavaScript Set objects, you can simply loop over the elements of Set "B" and remove elements that it has common with Set "A". This would leave you with all elements of "A" that are not elements of "B". For example:

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

    for (const elem of setB) {
        diff.delete(elem);
    }

    return diff;
}

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

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

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.