Sub topic 8
How Object.groupBy Converts Keys to Strings
This chapter assumes you have already called Object.groupBy with a key callback and know that its result is a null-prototype object. You should also be comfortable with template literals, JSON.stringify, and the basics of Map.
Your callback can return any value, but an object's property keys can only be strings or symbols. Object.groupBy closes that gap by converting each returned key with the same rule JavaScript uses for bracket access like obj[key]. The rule is simple. The bugs it causes show up because a conversion happens without any error or warning.
The Conversion Rule
For each element, Object.groupBy calls your callback and passes the result through the internal operation ToPropertyKey:
- If the value is a symbol, it stays a symbol.
- Otherwise it is converted to a primitive with the hint
"string", and then converted to a string.
Map.groupBy skips this step and keeps keys exactly as returned. That difference is the main reason to choose one method over the other, which a later chapter covers.
Common Values and What They Become
| Callback returns | Property key | Notes |
|---|---|---|
| `"fruit"` | `"fruit"` | Unchanged |
| `42` | `"42"` | Same key as the string `"42"` |
| `-0` | `"0"` | Merges with `0` |
| `NaN` | `"NaN"` | Every `NaN` lands in one group |
| `0.1 + 0.2` | `"0.30000000000000004"` | Floating-point noise becomes part of the key |
| `1e21` | `"1e+21"` | Large numbers use exponent form |
| `true` | `"true"` | Same key as the string `"true"` |
| `null` | `"null"` | |
| `undefined` | `"undefined"` | Often a sign of a typo in the callback |
| `{ id: 1 }` | `"[object Object]"` | Every plain object collides |
| `["EU", 2024]` | `"EU,2024"` | Arrays join with commas |
| `new Date(0)` | Long date string | Depends on the runtime's time zone |
| `Symbol("x")` | `Symbol(x)` | Kept as a symbol, hidden from `Object.keys` |
Different Types, Same Group
Because conversion happens before elements are compared, values of different types can share a group:
const mixed = [1, "1", 2, "2", "two"];
const byValue = Object.groupBy(mixed, (v) => v);
console.log(byValue["1"]); // [1, "1"]
console.log(byValue[2]); // [2, "2"]
console.log(Object.keys(byValue)); // ["1", "2", "two"]byValue[2] works because bracket access applies the same conversion, so 2 becomes "2" there too. Lookups are forgiving. Reading the keys back is less so. Object.keys and Object.entries always return strings, so numeric keys need converting back:
const ages = [12, 17, 23, 29, 31];
const byDecade = Object.groupBy(ages, (a) => Math.floor(a / 10) * 10);
console.log(Object.keys(byDecade)); // ["10", "20", "30"]
const decades = Object.keys(byDecade).map(Number);
console.log(decades); // [10, 20, 30]
console.log(decades[0] + 5); // 15, not "105"If you skip Number, "10" + 5 produces "105". That is a classic bug in code that summarizes grouped results.
The same merging happens for -0 and 0, for true and "true", and for null and "null". In most data this does no harm. It matters when one field holds mixed types, such as IDs that arrive as numbers from one API and as strings from another.
Objects Collapse into One Group
The most common mistake is returning an object from the callback and expecting one group per object:
const orders = [
{ id: 1, customer: { id: "c1", name: "Ada" } },
{ id: 2, customer: { id: "c2", name: "Lin" } },
{ id: 3, customer: { id: "c1", name: "Ada" } },
];
const wrong = Object.groupBy(orders, (o) => o.customer);
console.log(Object.keys(wrong)); // ["[object Object]"]
console.log(wrong["[object Object]"].length); // 3
const right = Object.groupBy(orders, (o) => o.customer.id);
console.log(Object.keys(right)); // ["c1", "c2"]
console.log(right.c1.map((o) => o.id)); // [1, 3]Every plain object converts to "[object Object]" through Object.prototype.toString, so all three orders end up in one group. You get no error. The fix is to return a primitive that identifies the object, usually an ID. If you need the object itself as the key, use Map.groupBy.
Composite Keys
To group by more than one field, build a single string. Returning an array looks like it works, because ["EU", 2024] becomes "EU,2024". But commas inside values make keys ambiguous: ["a,b", "c"] and ["a", "b,c"] both become "a,b,c". JSON.stringify avoids that problem, and JSON.parse turns the key back into its parts:
const sales = [
{ region: "EU", year: 2024, amount: 10 },
{ region: "EU", year: 2025, amount: 7 },
{ region: "US", year: 2024, amount: 4 },
{ region: "EU", year: 2024, amount: 3 },
];
const byRegionYear = Object.groupBy(sales, ({ region, year }) =>
JSON.stringify([region, year])
);
console.log(Object.keys(byRegionYear));
// ['["EU",2024]', '["EU",2025]', '["US",2024]']
for (const [key, rows] of Object.entries(byRegionYear)) {
const [region, year] = JSON.parse(key);
console.log(region, year, rows.length);
}
// EU 2024 2
// EU 2025 1
// US 2024 1A template literal with a separator that can't appear in the data, such as ` ${region}|${year} `, also works and gives more readable keys.
Custom Conversion and Its Failure Modes
Objects can control their own conversion. With the hint "string", JavaScript tries Symbol.toPrimitive first, then toString, then valueOf:
const tag = {
[Symbol.toPrimitive](hint) {
console.log("hint:", hint);
return "tagged";
},
};
const grouped = Object.groupBy([1, 2], () => tag);
// hint: string
// hint: string
console.log(Object.keys(grouped)); // ["tagged"]The conversion runs once per element, right after the callback returns. If conversion throws, Object.groupBy stops at that element and the error propagates. No partial result is returned:
const bad = {
toString() {
throw new Error("no key");
},
};
try {
Object.groupBy([1, 2, 3], (n) => (n === 2 ? bad : "ok"));
} catch (err) {
console.log(err.message); // "no key"
}
try {
Object.groupBy([1], () => Object.create(null));
} catch (err) {
console.log(err instanceof TypeError); // true
}The second case is easy to hit by accident. A null-prototype object has no toString or valueOf, so it can't become a primitive. That includes the result of another Object.groupBy call. Returning one as a key throws a TypeError.
Dates convert through Date.prototype.toString, which produces something like "Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)". The text depends on the machine's time zone, and the precision is one second. Return date.toISOString().slice(0, 10) for day buckets, or date.getTime() for exact instants.
Symbols Stay Symbols
Symbols are the one non-string key type that survives unchanged. Many common tools don't see them:
const PRIORITY = Symbol("priority");
const tasks = ["a", "b", "c"];
const grouped = Object.groupBy(tasks, (t) => (t === "b" ? PRIORITY : "normal"));
console.log(Object.keys(grouped)); // ["normal"]
console.log(grouped[PRIORITY]); // ["b"]
console.log(Reflect.ownKeys(grouped)); // ["normal", Symbol(priority)]
console.log(JSON.stringify(grouped)); // {"normal":["a","c"]}Object.keys, Object.entries, for...in, and JSON.stringify all skip symbol-keyed groups. Use Reflect.ownKeys or Object.getOwnPropertySymbols if you return symbols on purpose.
A Note on Special Key Names
Because the result has a null prototype and groups are created as own data properties, keys like "__proto__", "constructor", or "toString" become ordinary groups:
const odd = Object.groupBy(["x", "y"], (s) => (s === "x" ? "__proto__" : "constructor"));
console.log(Object.keys(odd)); // ["__proto__", "constructor"]
console.log(odd.__proto__); // ["x"]
console.log(Object.getPrototypeOf(odd)); // nullThis makes grouping safe for user-supplied strings. Be careful when you copy the result into an ordinary object, for example with { ...odd }. Spread defines own properties, so the copy is fine. Assigning in a loop, as in target[key] = value, would trigger the __proto__ setter on a normal object.
String conversion also affects the order of keys, because integer-like strings such as "10" and "2" are sorted first. The chapter on key ordering covers that.
Exercise
What does Object.keys(Object.groupBy([0, -0, NaN, "NaN", false, "0"], (v) => v)) return, and how many elements are in the group for "0"?
Show answer
It returns ["0", "NaN", "false"]. The values 0, -0, and "0" all convert to "0", so that group holds three elements: [0, -0, "0"]. NaN and "NaN" share the "NaN" group, and false becomes "false". "0" comes first because integer-like keys are ordered before other strings.
Exercise
A teammate writes Object.groupBy(events, (e) => e.createdAt) where createdAt is a Date, expecting one group per day. What goes wrong, and what callback fixes it?
Show answer
Each Date converts through Date.prototype.toString into a time-zone-dependent string with one-second precision, so events on the same day usually land in different groups. Return a day string instead: (e) => e.createdAt.toISOString().slice(0, 10), which groups by UTC calendar day.
Exercise
You group products by (p) => [p.brand, p.size]. Why can this give wrong groups, and what is a safer key?
Show answer
The array converts to a comma-joined string, so a brand containing a comma can collide with another brand and size pair. For example, ["A,B", "L"] and ["A", "B,L"] both become "A,B,L". Use (p) => JSON.stringify([p.brand, p.size]), which quotes each part, and read the parts back with JSON.parse.