Sub topic 2
The Old Way: Grouping with reduce
This chapter assumes you know how Array.prototype.reduce works, can write arrow functions with destructuring, and are comfortable reading and writing properties on plain objects. Before ES2024, grouping meant writing the logic yourself, usually with reduce or a loop. You will still see this pattern in older codebases. It also shows the problems the newer built-in methods solve.
The Accumulator Pattern
reduce walks an array and carries one value, the accumulator, from step to step. For grouping, the accumulator is an object that maps each key to an array of elements. On each step you compute the element's key, create an empty array for that key if none exists yet, push the element, and return the accumulator.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = inventory.reduce((groups, item) => {
const key = item.type;
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(item);
return groups;
}, {});
console.log(Object.keys(byType)); // ["vegetables", "fruit", "meat"]
console.log(byType.fruit.map((item) => item.name)); // ["bananas", "cherries"]The same logic written as a for...of loop is often easier to read, and it avoids having to return the accumulator:
const groups = {};
for (const item of inventory) {
(groups[item.type] ??= []).push(item);
}
console.log(groups.meat[0].name); // "goat"The ??= operator assigns a new array only when groups[item.type] is null or undefined, so the create-then-push steps fit on one line.
Common Errors
Hand-written grouping has a few well-known failure modes.
| Mistake | What happens |
|---|---|
| Forgetting `return groups` | The next step receives `undefined`, and `groups[key]` throws a `TypeError` |
| Omitting the initial `{}` | The first array element becomes the accumulator, so you get wrong results or a crash |
| Spreading a new object each step | `{ ...groups, [key]: [...] }` copies everything on every step, which costs O(n²) time |
| Keys that match inherited properties | Keys like `"toString"` or `"constructor"` collide with `Object.prototype` |
The last row is easy to miss. A {} literal inherits from Object.prototype, so groups["constructor"] already holds the Object function before you assign anything. The !groups[key] check passes over it, and .push fails:
const words = ["constructor", "apple"];
try {
words.reduce((groups, word) => {
if (!groups[word]) groups[word] = [];
groups[word].push(word);
return groups;
}, {});
} catch (err) {
console.log(err instanceof TypeError); // true
}To avoid the collision, start from Object.create(null), which creates an object with no prototype, or use a Map as the accumulator.
Exercise
Rewrite the reduce-based grouping so that a key such as "toString" groups correctly instead of throwing. Keep using reduce.
Show answer
Pass Object.create(null) as the initial value: words.reduce((groups, word) => { (groups[word] ??= []).push(word); return groups; }, Object.create(null)). The accumulator has no prototype, so groups["toString"] is undefined until you assign it. A new Map() accumulator also works, with groups.get and groups.set used for the lookups.
Exercise
Why is inventory.reduce((g, item) => ({ ...g, [item.type]: [...(g[item.type] ?? []), item] }), {}) slow on large arrays?
Show answer
Each step copies the whole accumulator object and the whole group array into new objects. The work per step grows with the number of elements already processed, so total time is quadratic. Mutating one accumulator inside reduce is safe and runs in linear time, because the accumulator is local to the call.