Sub topic 8
How Object.groupBy Converts Keys to Strings
This chapter assumes you already know how to call Object.groupBy with a key callback, and that you know what a null-prototype result object is. It also assumes you can explain the difference between a string and a symbol in JavaScript.
The key callback can return any value. The result is still a plain object, though, and a plain object's property keys can only be strings or symbols. Object.groupBy therefore converts each returned key to a property key before it stores the element. If you don't plan for that conversion, separate groups can merge without any warning.
The conversion rule
The spec runs each returned key through ToPropertyKey. A symbol stays a symbol. Every other value is converted to a string, the same way String(value) converts it.
The table shows common conversions:
| Returned key | Property key |
|---|---|
| `1` | `"1"` |
| `-0` | `"0"` |
| `true` | `"true"` |
| `null` | `"null"` |
| `undefined` | `"undefined"` |
| `[1, 2]` | `"1,2"` |
| `{ id: 1 }` | `"[object Object]"` |
| `Symbol("x")` | the same symbol |
Collisions: different values, same group
Two values that convert to the same string end up in the same group:
const mixed = [1, "1", true, "true", null, undefined];
const groups = Object.groupBy(mixed, (x) => x);
console.log(groups["1"]); // [1, "1"]
console.log(groups.true); // [true, "true"]
console.log(groups.null); // [null]
console.log(groups.undefined); // [undefined]The number 1 and the string "1" share a group, and so do true and "true". When a key from the callback is undefined because a property is missing, the element lands in a group literally named "undefined".
Objects cause the worst collisions. Unless an object defines its own toString, every object converts to "[object Object]":
const north = { region: "north" };
const south = { region: "south" };
const orders = [
{ id: 1, area: north },
{ id: 2, area: south },
];
const byArea = Object.groupBy(orders, (o) => o.area);
console.log(Object.keys(byArea)); // ["[object Object]"]
console.log(byArea["[object Object]"].length); // 2You wanted two groups and got one.
Avoiding surprises
Return an explicit string, so you choose the conversion yourself:
const orders = [
{ id: 1, area: { region: "north" }, size: "S" },
{ id: 2, area: { region: "south" }, size: "S" },
{ id: 3, area: { region: "north" }, size: "L" },
];
const byArea = Object.groupBy(orders, (o) => o.area.region);
console.log(Object.keys(byArea)); // ["north", "south"]
const byAreaAndSize = Object.groupBy(
orders,
(o) => `${o.area.region}|${o.size}`
);
console.log(Object.keys(byAreaAndSize)); // ["north|S", "south|S", "north|L"]A composite string such as "north|S" works well when you need to group on more than one field. Pick a separator that can't appear inside the values themselves.
Symbols are the one case where no conversion happens. They are useful for sentinel groups that can never collide with a string key:
const LOW = Symbol("low");
const groups = Object.groupBy([1, 5, 9], (n) => (n < 5 ? LOW : "high"));
console.log(groups[LOW]); // [1]
console.log(Object.keys(groups)); // ["high"]
console.log(Object.getOwnPropertySymbols(groups).length); // 1Object.keys and Object.entries skip symbol keys, so any code that loops over the result will not see symbol-keyed groups.
If you need groups whose keys keep their real type, such as objects or a number kept separate from a string, use Map.groupBy.
Exercise
What does Object.keys(Object.groupBy([0, -0, "0", [0]], (x) => x)) return, and how many elements does the single group hold?
Show answer
It returns ["0"]. The values 0 and -0 both convert to "0", the string "0" is already "0", and the array [0] converts to "0" as well, so all four elements share one group of length 4.
Exercise
A callback returns user.team, and some users have no team property. Where do those users go, and how would you give them a clearer group name?
Show answer
They go into a group with the key "undefined", because undefined converts to that string. Return a fallback such as user.team ?? "unassigned" to name the group explicitly.