Sub topic 4
Finding Common Elements with intersection
This chapter assumes you can create a Set, call has on it, and iterate it with for...of. It also assumes you know from the previous chapter that Set methods return a new Set and leave both inputs unchanged.
Set.prototype.intersection answers one question: which elements appear in both sets? It returns a new Set containing only those shared elements.
The Basic Call
You call intersection on one set and pass the other as the argument.
const alice = new Set(["hiking", "chess", "jazz", "cooking"]);
const bob = new Set(["jazz", "running", "chess"]);
const shared = alice.intersection(bob);
console.log(shared.size); // 2
console.log(shared.has("jazz")); // true
console.log(shared.has("hiking")); // false
console.log(alice.size); // 4 (unchanged)
console.log(bob.size); // 3 (unchanged)An element is in the result only if alice.has(element) and bob.has(element) are both true. Elements are compared with SameValueZero, the same rule has uses. So NaN matches NaN, and 0 matches -0.
It Is Symmetric
Swapping the receiver and the argument gives a set with the same elements, because "in both" means the same thing whichever set you start from.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
const ab = a.intersection(b);
const ba = b.intersection(a);
console.log(ab.size, ba.size); // 2 2
console.log([...ab].every((x) => ba.has(x))); // trueThis is different from difference, where a.difference(b) and b.difference(a) give different results. The next chapter covers that.
How It Works Internally
The engine avoids scanning the larger set. It compares the two sizes. Then it iterates whichever set is smaller and checks each element against the other with has. The cost therefore grows with the size of the smaller set, not the larger one.
This choice of which set to iterate also decides the order of the result. In the alice and bob example, bob is smaller, so the result comes out in bob's order:
const alice = new Set(["hiking", "chess", "jazz", "cooking"]);
const bob = new Set(["jazz", "running", "chess"]);
console.log([...alice.intersection(bob)]); // ["jazz", "chess"]A later chapter covers ordering in detail. For now, do not rely on intersection keeping the receiver's order.
Intersecting More Than Two Sets
intersection takes one argument. To find elements common to many sets, chain calls or use reduce:
const week1 = new Set([101, 102, 103, 104]);
const week2 = new Set([102, 103, 104]);
const week3 = new Set([103, 104, 105]);
const everyWeek = [week1, week2, week3].reduce((acc, s) => acc.intersection(s));
console.log(everyWeek.size); // 2
console.log(everyWeek.has(103)); // true
console.log(everyWeek.has(102)); // falseEach step produces a new Set no larger than the smallest set so far, so the later steps stay cheap. Call reduce without an initial value here. If you seed it with an empty Set, every result will be empty.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Passing an array: `s.intersection([1, 2])` | `TypeError`, because arrays have no `size` | Wrap it: `s.intersection(new Set([1, 2]))` |
| Expecting an empty result to be `null` | You always get a Set, possibly with `size` 0 | Check `result.size === 0` |
| Expecting objects with equal contents to match | Only the same reference matches | Intersect IDs or other primitive keys instead |
| Assuming the receiver's order is kept | The order may follow the argument | Sort the result if order matters |
Exercises
Exercise
Given const x = new Set(["a", "b", "c"]) and const y = new Set(["c", "d"]), what are the size of x.intersection(y), the size of y.intersection(x), and the size of x after both calls?
Show answer
Both intersections have size 1 and contain only "c". x still has size 3, because intersection returns a new Set and does not modify either input.
Exercise
A teammate writes [s1, s2, s3].reduce((acc, s) => acc.intersection(s), new Set()) and always gets an empty result. Why, and how do you fix it?
Show answer
The empty Set seed shares no elements with anything, so the first step returns an empty Set and every later step stays empty. Remove the initial value so reduce starts from s1, or seed it with s1 and reduce over the remaining sets.