How to Get the Intersection of Two Sets in JavaScript?

One of the basic Set operations is to get the intersection of two sets. In mathematical terms, this is expressed as A ∩ B (i.e. elements that are common in both "A" and "B").

To get the intersection of two JavaScript Set objects, you can loop over one of the Set objects, and check which elements are common between the two by using the Set.prototype.has() method on the other Set. For example:

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

    for (const elem of setA) {
        if (setB.has(elem)) {
            result.add(elem);
        }
    }

    return result;
}

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

console.log(intersection(setA, setB)); // Set(2) {3, 4}

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.