How to Get the Union of Two Sets in JavaScript?

Find out how to combine all elements of two JavaScript Sets into one

In mathematical terms, the union of two sets is expressed as A ∪ B (i.e. set of all elements that exist in "A" and "B").

To get the union of two JavaScript Set objects, you can simply add all values from one Set to the other like so:

For example:

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

    for (const elem of setB) {
        union.add(elem);
    }

    return union;
}

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

console.log(union(setA, setB)); // Set(6) {1, 2, 3, 4, 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.


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