Sub topic 4
Finding Common Elements with intersection
Set.prototype.intersection answers one question: which elements are in both sets? It returns a new Set that holds only those shared elements. This chapter covers how the method works, the order its results come in, how it compares tricky values, and the mistakes developers make most often.
This chapter assumes you already know how to create and iterate a Set, use spread syntax and Array.prototype.filter, and write arrow functions. It also assumes you have read the earlier chapter explaining that the new Set methods return fresh sets and never change their inputs.
The Working Model
The method call a.intersection(b) produces a set containing every value x for which both a.has(x) and b.has(x) are true. Neither a nor b changes.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
const common = a.intersection(b);
console.log(common.size); // 2
console.log([...common]); // [3, 4]
console.log(a.size, b.size); // 4 3 (both unchanged)
console.log(common instanceof Set); // trueThe return value is always a real Set, even when nothing overlaps. Two sets with no shared elements give an empty set, not null or undefined:
const evens = new Set([2, 4, 6]);
const odds = new Set([1, 3, 5]);
const none = evens.intersection(odds);
console.log(none.size); // 0
console.log(none instanceof Set); // trueYou can therefore call .size, .has, or another Set method on the result without checking for a missing value first.
Intersection with an empty set
Intersecting with an empty set always gives an empty set, whichever side the empty set is on. Intersecting a set with itself gives a copy of that set:
const tags = new Set(["js", "css"]);
const empty = new Set();
console.log(tags.intersection(empty).size); // 0
console.log(empty.intersection(tags).size); // 0
const copy = tags.intersection(tags);
console.log([...copy]); // ["js", "css"]
console.log(copy === tags); // false (a new Set)How the Engine Computes It
The specification does not loop over the receiver every time. It compares the two sizes and iterates whichever set is smaller, checking each element against the other one. This keeps the work proportional to the smaller set.
In outline, the algorithm is:
- If
this.size <= other.size, walk through the elements ofthisin insertion order and callother.has(x)for each one. Keep the elements that returntrue. - Otherwise, walk through
other.keys()and keep each value thatthisalready contains. - Return a new
Setholding the kept elements.
The method calls has on the argument in the first branch and keys in the second. That is why the argument only has to be set-like rather than a real Set. A later chapter covers that protocol in detail.
Performance compared with arrays
Before ES2025, many codebases found common elements with nested array scans:
const listA = [1, 2, 3, 4];
const listB = [3, 4, 5];
// O(n * m): includes scans listB for every element of listA
const slow = listA.filter((x) => listB.includes(x));
console.log(slow); // [3, 4]Each includes call is a linear search, so this runs in O(n × m) time. Hashing makes Set.prototype.has close to constant time, so intersection runs in roughly O(min(n, m)). With two lists of 50,000 IDs, the array version does up to 2.5 billion comparisons. The Set version does about 50,000 lookups.
Result Order: The Smaller Set Wins
The algorithm iterates the smaller set, so the result takes its order from the smaller set, not always from the receiver. Most developers expect the receiver's order, and this behavior surprises them.
const big = new Set(["c", "b", "a", "z"]);
const small = new Set(["a", "b", "c"]);
console.log([...big.intersection(small)]); // ["a", "b", "c"]
console.log([...small.intersection(big)]); // ["a", "b", "c"]big is the receiver in the first call, but small has fewer elements, so the engine iterates small and its order wins. When the sizes are equal, the receiver is iterated, and swapping the operands changes the order:
const x = new Set([1, 2, 3]);
const y = new Set([3, 2, 1]);
console.log([...x.intersection(y)]); // [1, 2, 3]
console.log([...y.intersection(x)]); // [3, 2, 1]The two results always contain the same elements. Intersection is commutative in its contents but not always in its order.
How Elements Are Compared
Intersection uses the same equality as the rest of Set, called SameValueZero. Three consequences matter in practice.
NaN matches NaN
With ===, NaN is never equal to itself. Under SameValueZero it is, so NaN survives an intersection when both sets contain it:
const a = new Set([NaN, 1]);
const b = new Set([NaN, 2]);
const common = a.intersection(b);
console.log(common.size); // 1
console.log(common.has(NaN)); // true+0 and -0 are the same element
const a = new Set([0]);
const b = new Set([-0]);
const common = a.intersection(b);
console.log(common.size); // 1
console.log(Object.is([...common][0], -0)); // false (stored as +0)The specification normalizes -0 to +0 when it adds a value from the argument's keys() to the result. You will always see +0 in the output.
Types are not coerced
The number 1 and the string "1" are different elements. This catches people who intersect IDs read from a URL or form, which arrive as strings, with IDs from a database, which are often numbers:
const fromQuery = new Set(["1", "2", "3"]);
const fromDb = new Set([2, 3, 4]);
console.log(fromQuery.intersection(fromDb).size); // 0
const normalized = new Set([...fromQuery].map(Number));
console.log([...normalized.intersection(fromDb)]); // [2, 3]Normalize the types before you intersect. Objects follow a stricter rule: two objects match only if they are the same reference. The chapter "Objects in Sets: Reference Equality" covers that case.
Intersecting More Than Two Sets
intersection takes exactly one argument. To intersect many sets, chain the calls or fold them with reduce:
const monday = new Set(["ana", "ben", "cai", "dev"]);
const tuesday = new Set(["ben", "cai", "eli"]);
const wednesday = new Set(["cai", "ben", "fay"]);
const chained = monday.intersection(tuesday).intersection(wednesday);
console.log([...chained]); // ["ben", "cai"]
function intersectAll(sets) {
if (sets.length === 0) return new Set();
return sets.reduce((acc, s) => acc.intersection(s));
}
console.log([...intersectAll([monday, tuesday, wednesday])]); // ["ben", "cai"]Each intermediate result can only shrink, so starting with the smallest set keeps every step cheap. Sorting by size first also lets you stop early once the accumulator is empty:
function intersectAllFast(sets) {
if (sets.length === 0) return new Set();
const sorted = [...sets].sort((p, q) => p.size - q.size);
let acc = sorted[0];
for (let i = 1; i < sorted.length && acc.size > 0; i++) {
acc = acc.intersection(sorted[i]);
}
// Ensure a new Set is returned even when only one set was passed
return acc === sorted[0] ? new Set(acc) : acc;
}
const result = intersectAllFast([
new Set([1, 2, 3, 4, 5, 6]),
new Set([2, 4]),
new Set([4, 2, 9]),
]);
console.log([...result]); // [2, 4]Decide on purpose what an empty list of sets should return. Mathematically, the intersection of zero sets is "everything", which cannot be represented. Returning an empty set is the usual practical choice, but document it.
A Practical Example: Mutual Followers
A common task is finding users who follow each other. Store each user's follow list as a set of IDs, then intersect:
const following = new Map([
["ana", new Set(["ben", "cai", "dev"])],
["ben", new Set(["ana", "cai"])],
["cai", new Set(["dev"])],
["dev", new Set(["ana", "cai"])],
]);
function followers(user) {
const result = new Set();
for (const [name, targets] of following) {
if (targets.has(user)) result.add(name);
}
return result;
}
function mutuals(user) {
return following.get(user).intersection(followers(user));
}
console.log([...mutuals("ana")].sort()); // ["ben", "dev"]
console.log([...mutuals("cai")].sort()); // ["dev"]Ana follows ben, cai, and dev. Her followers are ben and dev. The intersection is ben and dev. The code sorts the output because, as shown earlier, intersection does not promise the receiver's order.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Passing an array: `a.intersection([1, 2])` | `TypeError`, because arrays have no `size` property | Wrap it: `a.intersection(new Set(arr))` |
| Expecting `a` to be modified | `a` is unchanged and the result is discarded | Assign the result: `a = a.intersection(b)` |
| Expecting an array back | `.map` or `.length` is `undefined` on the result | Spread it: `[...a.intersection(b)]` |
| Assuming receiver order | The order follows the smaller set | Sort the result explicitly |
| Mixing `"1"` and `1` | No matches | Normalize types first |
| Intersecting sets of fresh objects | No matches unless the references are shared | Intersect on IDs, then look up the objects |
The array case deserves a closer look because it fails loudly:
const ids = new Set([1, 2, 3]);
try {
ids.intersection([2, 3]);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log([...ids.intersection(new Set([2, 3]))]); // [2, 3]Exercises
Exercise
Given const a = new Set([1, 2, 3, 4, 5]) and const b = new Set([5, 3, 1]), what does console.log([...a.intersection(b)]) print, and why?
Show answer
It prints [5, 3, 1]. a.size (5) is greater than b.size (3), so the engine iterates b.keys() and keeps each value that a contains. The result therefore follows b's insertion order, not a's.
Exercise
What is the size of new Set([NaN, 0, "0"]).intersection(new Set([NaN, -0, 0n]))?
Show answer
2. NaN matches NaN and 0 matches -0 under SameValueZero. The string "0" and the BigInt 0n are different types from each other and from the number 0, so neither of them matches anything.
Exercise
Write a function sharedTags(posts) that takes an array of post objects, each with a tags array, and returns a Set of the tags that appear on every post. Return an empty Set when posts is empty.
Show answer
function sharedTags(posts) { if (posts.length === 0) return new Set(); return posts.map((p) => new Set(p.tags)).reduce((acc, s) => acc.intersection(s)); } Each tags array must be wrapped in new Set(...) because intersection throws a TypeError when given an array.
Exercise
A teammate writes let active = new Set(ids); active.intersection(allowed); console.log(active.size); and is surprised that the size never changes. Explain the bug and fix it.
Show answer
intersection returns a new Set and leaves active unchanged, so the result is thrown away. Assign it instead: active = active.intersection(allowed); or store it in a new variable, for example const permitted = active.intersection(allowed).