How to Get the Union of Two Sets in JavaScript?

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.


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.