Sub topic 8
Objects in Sets: Reference Equality
This chapter assumes you know how to create a Set and use has, that you have used intersection and difference, and that you understand the difference between primitive values and object references. Here we look at what happens when the elements of a Set are objects rather than strings or numbers.
How Set Methods Compare Elements
Every Set method decides whether two elements are "the same" using an algorithm called SameValueZero. It works like === with two exceptions. NaN equals NaN, and +0 equals -0. For primitives, this usually gives the result you expect:
const a = new Set([NaN, 0, "x"]);
const b = new Set([NaN, -0, "x"]);
console.log(a.intersection(b).size); // 3 (NaN, 0, and "x" all match)For objects, SameValueZero compares references, not contents. Two object literals are two separate objects in memory, even when they have the same properties. They match only when both sets hold the exact same reference.
The Common Mistake
Suppose you load two lists of users from different API calls and want the users that appear in both:
const morning = new Set([{ id: 1, name: "Ada" }, { id: 2, name: "Lin" }]);
const evening = new Set([{ id: 2, name: "Lin" }, { id: 3, name: "Sam" }]);
console.log(morning.intersection(evening).size); // 0
console.log(morning.difference(evening).size); // 2The intersection is empty because each API response created new objects. The { id: 2 } in morning and the { id: 2 } in evening are different references, so the methods treat them as unrelated. The code raises no error and quietly gives the wrong answer.
The same rule applies to arrays, because arrays are objects:
const points = new Set([[0, 0], [1, 1]]);
console.log(points.has([0, 0])); // falseWhen References Do Match
If both sets hold the same object, the methods find it:
const ada = { id: 1, name: "Ada" };
const team = new Set([ada, { id: 2, name: "Lin" }]);
const admins = new Set([ada]);
console.log(team.intersection(admins).has(ada)); // true
console.log(team.difference(admins).size); // 1This happens when your objects come from one shared source, such as a single store, a cache, or one array that you filter in several ways.
Fix 1: Compare Keys, Then Map Back
The most reliable fix is to build sets of primitive keys, such as IDs, run the set operation on those keys, and then look up the full objects:
const morningUsers = [{ id: 1, name: "Ada" }, { id: 2, name: "Lin" }];
const eveningUsers = [{ id: 2, name: "Lin" }, { id: 3, name: "Sam" }];
const morningIds = new Set(morningUsers.map((u) => u.id));
const eveningIds = new Set(eveningUsers.map((u) => u.id));
const sharedIds = morningIds.intersection(eveningIds);
const sharedUsers = morningUsers.filter((u) => sharedIds.has(u.id));
console.log(sharedUsers); // [{ id: 2, name: "Lin" }]This works because numbers and strings are compared by value.
Fix 2: Canonicalize Objects
If you need sets of the objects themselves, make sure each logical entity has only one object. A Map keyed by ID can act as a registry:
const registry = new Map();
function canonical(user) {
if (!registry.has(user.id)) registry.set(user.id, user);
return registry.get(user.id);
}
const a = new Set([{ id: 1 }, { id: 2 }].map(canonical));
const b = new Set([{ id: 2 }, { id: 3 }].map(canonical));
console.log(a.intersection(b).size); // 1| Approach | Good for | Watch out for |
|---|---|---|
| Compare ID sets | Most data from APIs or databases | You need an extra lookup to get the objects back |
| Canonical registry | Long-lived app state | The registry keeps objects in memory |
| `JSON.stringify` keys | Quick scripts | Property order changes the string |
Exercise
Given const x = { n: 1 }; const s1 = new Set([x, { n: 2 }]); const s2 = new Set([{ n: 1 }, { n: 2 }]);, what is s1.intersection(s2).size, and what is new Set([NaN]).isSubsetOf(new Set([NaN]))?
Show answer
s1.intersection(s2).size is 0. Every object in s2 is a different reference from the objects in s1, including the one that looks like x. new Set([NaN]).isSubsetOf(new Set([NaN])) is true, because SameValueZero treats NaN as equal to NaN.
Exercise
You have two arrays of product objects, cart and inStock, each with a string sku property. Write code that returns the cart products that are not in stock.
Show answer
Build a set of in-stock SKUs and filter the cart against it: const stockSkus = new Set(inStock.map((p) => p.sku)); const missing = cart.filter((p) => !stockSkus.has(p.sku));. You could also run difference on two SKU sets and then filter cart by the result. Calling difference on sets of the product objects would fail, because those objects are different references.