Code Snippets
/

Set Intersection and Difference

Set Intersection and Difference

Computing the items shared between two arrays, the items in the first but not the second, or the symmetric difference is a routine task: comparing API responses, diffing user selections, finding new vs. removed records. This snippet shows the classic `Set`-backed implementations, an object-aware `byKey` variant, and the new native `Set.prototype.intersection` / `difference` methods that landed in Node 22 and 2024 browsers.

JavaScript
Medium
4 snippets
arrays
set
utility
sets-logic

758 views

6

function intersection(a, b) {
    const setB = new Set(b);
    return [...new Set(a)].filter((x) => setB.has(x));
}

function difference(a, b) {
    const setB = new Set(b);
    return [...new Set(a)].filter((x) => !setB.has(x));
}

function symmetricDifference(a, b) {
    const setA = new Set(a);
    const setB = new Set(b);
    const out = [];
    for (const x of setA) if (!setB.has(x)) out.push(x);
    for (const x of setB) if (!setA.has(x)) out.push(x);
    return out;
}

const a = [1, 2, 3, 4];
const b = [3, 4, 5, 6];

console.log(intersection(a, b));        // [3, 4]
console.log(difference(a, b));          // [1, 2]
console.log(difference(b, a));          // [5, 6]
console.log(symmetricDifference(a, b)); // [1, 2, 5, 6]

All three operations boil down to a hash lookup against the other side. Building one Set from b makes every membership test O(1), so the overall pass is O(|a| + |b|) instead of the O(|a| * |b|) you would get from array.includes in a filter. Wrapping a in a fresh Set first dedupes the result, which matches the mathematical definition of these operations. Note that difference is asymmetric: difference(a, b) is "in a, not in b", and symmetricDifference is the union of both halves.