How to Get the Difference of Two Sets in JavaScript?

Find out how to get the difference of two JavaScript Sets

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}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.