Sub topic 7
Using Objects and Other Non-String Values as Keys
This chapter assumes you already know how Map.groupBy works: it takes an iterable and a key callback, and it returns a Map from each key to an array of elements. You should also know basic Map methods (get, has, keys) and the difference between primitive values and object references.
Map.groupBy lets the key be any value: an object, an array, a Date, NaN, undefined, or a symbol. That freedom comes with one rule. To decide whether two keys are the same, the method uses SameValueZero, the same comparison that Map itself uses. If you misunderstand SameValueZero, you can end up with one group per element when you expected a few groups, or you can call get and receive undefined for a group that exists.
What SameValueZero Compares
SameValueZero is the equality algorithm behind Map, Set, and Array.prototype.includes. It works almost exactly like ===, with two differences:
NaNequalsNaN. With===,NaN === NaNisfalse.+0and-0are equal, as they are with===. (Object.istreats them as different.)
For objects, including arrays, functions, and Date instances, SameValueZero compares identity. Two objects match only if they are the same object in memory. Their contents do not matter.
| Key pair | `===` | SameValueZero | `Object.is` |
|---|---|---|---|
| `"fruit"`, `"fruit"` | true | true | true |
| `1`, `"1"` | false | false | false |
| `NaN`, `NaN` | false | true | true |
| `0`, `-0` | true | true | false |
| `{}`, `{}` (two literals) | false | false | false |
| `obj`, `obj` (same reference) | true | true | true |
| `[1, 2]`, `[1, 2]` | false | false | false |
Primitive Edge Cases: NaN and Negative Zero
Since SameValueZero treats NaN as equal to itself, every NaN the callback returns lands in one group. This is handy when you parse numbers and want to collect the failures:
const inputs = ["1", "abc", "2", "x", "1"];
const byNumber = Map.groupBy(inputs, (s) => Number(s));
console.log([...byNumber.keys()]); // [1, NaN, 2]
console.log(byNumber.get(NaN)); // ["abc", "x"]
console.log(byNumber.get(1)); // ["1", "1"]Negative zero gets one more step. Before storing a key, Map.groupBy converts -0 to +0, which is what Map.prototype.set does too. The two values share a group, and the stored key is always +0:
const groups = Map.groupBy([-0, 0, 5], (n) => n);
const keys = [...groups.keys()];
console.log(keys.length); // 2
console.log(Object.is(keys[0], -0)); // false
console.log(groups.get(-0).length); // 2You can look the group up with either 0 or -0. If you have code that checks Object.is(key, -0), it will never match a key read back from the result.
Grouping by an Existing Object
Object keys are most useful when you already hold the object, for example when each record points to a shared parent object. The key callback returns that reference, and every record that points to the same parent goes into one group:
const ana = { id: 1, name: "Ana" };
const ben = { id: 2, name: "Ben" };
const orders = [
{ id: "o1", customer: ana, total: 30 },
{ id: "o2", customer: ben, total: 12 },
{ id: "o3", customer: ana, total: 8 },
];
const byCustomer = Map.groupBy(orders, (order) => order.customer);
for (const [customer, list] of byCustomer) {
console.log(customer.name, list.map((o) => o.id));
}
// Ana ["o1", "o3"]
// Ben ["o2"]
console.log(byCustomer.get(ana).length); // 2
console.log(byCustomer.get({ id: 1, name: "Ana" })); // undefinedA string key would make you look the customer up again. Here each key is the customer object itself, so customer.name is available inside the loop.
The last line shows the most common mistake. An object literal that looks the same as ana is a different object, so the lookup fails. To read a group you must keep the original reference, or search the keys:
const ana = { id: 1, name: "Ana" };
const byCustomer = Map.groupBy([{ customer: ana }], (o) => o.customer);
const key = [...byCustomer.keys()].find((c) => c.id === 1);
console.log(byCustomer.get(key).length); // 1That search scans every key. If you need lookups by id often, a primitive key such as customer.id is the better choice.
When Every Element Gets Its Own Group
Identity comparison causes trouble when the callback builds a new object on each call. Two patterns come up often.
Composite keys built as arrays
Grouping by two fields with an array key looks natural, but each call returns a new array:
const items = [
{ type: "shirt", size: "M" },
{ type: "shirt", size: "M" },
{ type: "shirt", size: "L" },
];
const bad = Map.groupBy(items, ({ type, size }) => [type, size]);
console.log(bad.size); // 3
const good = Map.groupBy(items, ({ type, size }) => `${type}|${size}`);
console.log(good.size); // 2
console.log(good.get("shirt|M").length); // 2The string version works because strings compare by value. Pick a separator that cannot appear inside the fields, or use JSON.stringify([type, size]), which escapes the parts safely.
Data deserialized from JSON
When records come from JSON.parse or an API, each nested object is a separate copy, even when two of them describe the same customer. Grouping by order.customer then gives one group per order. Normalize first: build a lookup of canonical objects and return the canonical one from the callback.
const payload = JSON.parse(`{
"customers": [{ "id": 1, "name": "Ana" }, { "id": 2, "name": "Ben" }],
"orders": [
{ "id": "o1", "customer": { "id": 1, "name": "Ana" } },
{ "id": "o2", "customer": { "id": 2, "name": "Ben" } },
{ "id": "o3", "customer": { "id": 1, "name": "Ana" } }
]
}`);
const naive = Map.groupBy(payload.orders, (o) => o.customer);
console.log(naive.size); // 3
const customersById = new Map(payload.customers.map((c) => [c.id, c]));
const byCustomer = Map.groupBy(payload.orders, (o) =>
customersById.get(o.customer.id)
);
console.log(byCustomer.size); // 2
console.log(byCustomer.get(customersById.get(1)).map((o) => o.id)); // ["o1", "o3"]Dates
Date objects are objects, so two Date instances for the same moment are still different keys. Use a primitive derived from the date: getTime() for exact instants, or a YYYY-MM-DD string for calendar days.
const events = [
{ name: "deploy", at: new Date("2024-03-01T09:00:00Z") },
{ name: "rollback", at: new Date("2024-03-01T15:30:00Z") },
{ name: "deploy", at: new Date("2024-03-02T10:00:00Z") },
];
const byDay = Map.groupBy(events, (e) => e.at.toISOString().slice(0, 10));
console.log([...byDay.keys()]); // ["2024-03-01", "2024-03-02"]
console.log(byDay.get("2024-03-01").length); // 2Interning: Composite Keys You Can Destructure
Sometimes you want structured keys, such as [type, size] pairs you can destructure while iterating, and you also want them to group correctly. Interning gives you both. An interner keeps a cache that maps a string id to one canonical key object, so equal parts always produce the same reference.
function makeInterner() {
const cache = new Map();
return (...parts) => {
const id = JSON.stringify(parts);
let key = cache.get(id);
if (key === undefined) {
key = Object.freeze(parts);
cache.set(id, key);
}
return key;
};
}
const items = [
{ type: "shirt", size: "M", price: 20 },
{ type: "shirt", size: "M", price: 22 },
{ type: "hat", size: "L", price: 15 },
];
const keyOf = makeInterner();
const grouped = Map.groupBy(items, ({ type, size }) => keyOf(type, size));
for (const [[type, size], list] of grouped) {
console.log(type, size, list.length);
}
// shirt M 2
// hat L 1
console.log(grouped.get(keyOf("shirt", "M")).length); // 2Freezing the key stops anyone from mutating it after it has been used. A mutated key would still sit in the same group, because the Map tracks identity and never looks at contents, but its contents would no longer describe the group.
Other Non-String Keys
Map.groupBy stores every other key type exactly as returned:
- Numbers and booleans keep their type, so
get(1)andget("1")are different lookups. undefinedandnullare valid, separate keys. A callback that forgets areturnin a braced arrow function sends every element to theundefinedgroup. That bug is easy to miss.- Symbols compare by identity, like objects.
Symbol("x")called twice gives two keys, whileSymbol.for("x")returns the same registered symbol each time. - Functions work as identity keys. You can group tasks by their handler function, for example.
Exercise
You run Map.groupBy(points, (p) => ({ x: p.x })) on 50 points that have only 3 distinct x values. How many groups does the result contain, and how would you change the callback to get 3?
Show answer
It contains 50 groups. Each call creates a new object literal, and SameValueZero compares objects by reference, so no two keys match. Return a primitive instead, such as (p) => p.x, or return an interned object, such as keyOf(p.x) from an interner like the one in this chapter.
Exercise
Given const m = Map.groupBy(["a", "1", "b", "0", "-0"], Number);, what does [...m.keys()] contain, and what does m.get(-0) return?
Show answer
Number maps the inputs to NaN, 1, NaN, 0, -0. Both NaN values share one group, and -0 is normalized to +0 and joins the 0 group. The keys are [NaN, 1, 0], and m.get(-0) returns ["0", "-0"].
Exercise
Orders arrive from an API, and each order contains its own copy of a warehouse object with an id. You want a Map whose keys are warehouse objects, so you can read warehouse.name while iterating. Describe the approach.
Show answer
Build a canonical lookup first, for example const byId = new Map(warehouses.map((w) => [w.id, w])), or by keeping the first copy seen for each id. Then group with Map.groupBy(orders, (o) => byId.get(o.warehouse.id)), so every order for the same warehouse returns the same reference.