Sub topic 2
The Old Way: Grouping with reduce
Before ES2024, JavaScript had no built-in way to group values. Developers wrote the grouping logic themselves, usually with Array.prototype.reduce or a plain loop. You will see this code in almost every older codebase. It also helps you see what Object.groupBy and Map.groupBy do for you, because they do the same work with fewer chances to make a mistake.
This chapter assumes you know how reduce works: it takes a callback and an initial value, and the callback's return value becomes the accumulator for the next element. It also assumes you are comfortable with arrow functions, destructuring, object property access, basic Map methods, and the ?? and ||= operators.
The standard reduce pattern
The usual approach starts from an empty object. For each element, the code works out a key, creates an array under that key if there is none yet, pushes the element into it, and returns 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"]Each pass through the callback follows the same steps. The diagram shows the loop that reduce runs.
You will often see a shorter version that uses logical OR assignment or nullish assignment:
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) => {
(groups[item.type] ??= []).push(item);
return groups;
}, {});
console.log(byType.meat[0].name); // "goat"Both versions work for this data. The trouble is that every developer writes this pattern by hand, and it is easy to get one of its parts wrong.
Common errors in hand-written grouping
Forgetting to return the accumulator
With a block-bodied arrow function, leaving out return groups makes the callback return undefined. The next call then receives undefined as its accumulator.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
];
try {
inventory.reduce((groups, item) => {
(groups[item.type] ??= []).push(item);
// missing: return groups;
}, {});
} catch (error) {
console.log(error instanceof TypeError); // true
}The first element is grouped correctly. The second call then fails when it tries to read a property of undefined. At least this error is loud.
Forgetting the initial value
If you leave out the {} argument, reduce uses the first element as the accumulator and starts with the second element. Nothing throws. The groups get written onto your first data object instead.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const broken = inventory.reduce((groups, item) => {
(groups[item.type] ??= []).push(item);
return groups;
});
console.log(broken === inventory[0]); // true
console.log(broken.fruit.length); // 2
console.log(broken.vegetables); // undefinedThis mistake is worse than the missing return. The asparagus item is never placed in a group, and the source object now has a fruit property it did not have before.
Keys that collide with Object.prototype
A {} accumulator inherits from Object.prototype. Keys such as "constructor", "toString", and "__proto__" already resolve to inherited values, so the "does this group exist?" check gives the wrong answer.
const words = ["apple", "constructor", "toString"];
try {
words.reduce((groups, word) => {
(groups[word] ||= []).push(word);
return groups;
}, {});
} catch (error) {
console.log(error.message.includes("push")); // true
}groups["constructor"] is the Object function, which is truthy. Because of that, ||= never creates an array, and calling .push on a function throws. When keys come from user input, such as tags, usernames, or CSV headers, this bug can show up in production long after the code was written.
The fix is an accumulator with no prototype:
const words = ["apple", "constructor", "toString", "__proto__"];
const groups = words.reduce((acc, word) => {
(acc[word] ??= []).push(word);
return acc;
}, Object.create(null));
console.log(Object.keys(groups)); // ["apple", "constructor", "toString", "__proto__"]
console.log(Object.getPrototypeOf(groups)); // nullObject.groupBy makes this same choice for you, which a later chapter covers in detail.
The spread-accumulator trap
Code written in an immutable style often builds a new object on every step:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = inventory.reduce(
(groups, item) => ({
...groups,
[item.type]: [...(groups[item.type] ?? []), item],
}),
{}
);
console.log(byType.fruit.length); // 2The result is correct, but each step copies every existing key and the whole target array. The total work grows roughly with the square of the input size. With a few dozen items you won't notice. With tens of thousands of items, the slowdown is easy to measure. The accumulator is a fresh object that nothing else can see, so mutating it inside reduce is safe and is the normal approach.
The table lists these errors and what each one looks like when it happens.
| Mistake | Symptom | Fix |
|---|---|---|
| No `return groups` | TypeError on the second element | Return the accumulator, or use a loop |
| No initial value | Silent wrong result, first element mutated | Always pass `{}` or `Object.create(null)` |
| `{}` with untrusted keys | TypeError or wrong groups for `"constructor"`, `"__proto__"` | Use `Object.create(null)` or a `Map` |
| Spreading the accumulator | Correct output, very slow on large input | Mutate the accumulator |
Grouping with a loop instead
Many developers find a for...of loop clearer than reduce for grouping, because there is no accumulator to thread through and no return to forget. A loop also works on any iterable, while reduce only exists on arrays. To group a string or a Set with reduce, you first have to convert it with Array.from or spread syntax.
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 byStock = Object.create(null);
for (const item of inventory) {
const key = item.quantity > 5 ? "ok" : "restock";
(byStock[key] ??= []).push(item);
}
console.log(byStock.restock.length); // 3
console.log(byStock.ok[0].name); // "goat"Grouping into a Map with reduce
When keys are not strings, such as booleans, numbers you want to keep as numbers, or objects, the older code used a Map as the accumulator:
const numbers = [1, 2, 3, 4, 5];
const byParity = numbers.reduce((groups, n, index) => {
const key = n % 2 === 0;
const list = groups.get(key);
if (list) {
list.push({ n, index });
} else {
groups.set(key, [{ n, index }]);
}
return groups;
}, new Map());
console.log([...byParity.keys()]); // [false, true]
console.log(byParity.get(true).map((entry) => entry.n)); // [2, 4]
console.log(byParity.get(false)[2].index); // 4The index comes from reduce's third callback argument. The built-in grouping methods pass the index as the callback's second argument, because they have no accumulator.
Libraries filled the gap
Since this pattern came up so often, utility libraries shipped it. Lodash's _.groupBy(collection, iteratee) returns a plain object, and many projects installed Lodash mainly for this one function. If you migrate such code, check two details. Lodash's result has a normal prototype, unlike Object.groupBy's. Lodash also accepts a property-name string as the iteratee (_.groupBy(items, "type")), while the built-in methods require a function.
What the built-in methods remove
Compare the reduce version with the ES2024 version of the same task. The built-in call has no accumulator to initialize, no return to forget, and no array creation to write, and it already uses a null prototype:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const viaReduce = inventory.reduce((groups, item) => {
(groups[item.type] ??= []).push(item);
return groups;
}, Object.create(null));
const viaGroupBy = Object.groupBy(inventory, (item) => item.type);
console.log(JSON.stringify(viaReduce) === JSON.stringify(viaGroupBy)); // trueYou still need the reduce and loop patterns for runtimes that lack groupBy, and for cases where you want to build a summary in one pass instead of grouping first. The next chapter starts on the built-in methods.
Exercise
A teammate wrote const byTag = posts.reduce((acc, p) => { acc[p.tag] = acc[p.tag] || []; acc[p.tag].push(p); return acc; }, {});. It works in tests but crashes in production on a post tagged "constructor". Explain why, and give a one-change fix.
Show answer
The accumulator {} inherits from Object.prototype, so acc["constructor"] is the Object function. That value is truthy, so acc[p.tag] || [] keeps the function, and .push on a function throws a TypeError. Replace the initial value {} with Object.create(null). That object has no inherited properties, so every tag starts out undefined.
Exercise
What does [{ k: "a" }, { k: "b" }, { k: "a" }].reduce((g, x) => { (g[x.k] ??= []).push(x); return g; }) return, and what happened to the first element?
Show answer
No initial value was passed, so the first element { k: "a" } becomes the accumulator and reduce starts at the second element. The call returns that same first object, which now also has a b property holding the second element and an a property holding the third. The first element is never placed in any group, and the source data has been mutated.
Exercise
Rewrite the spread-based reducer items.reduce((g, i) => ({ ...g, [i.type]: [...(g[i.type] ?? []), i] }), {}) so it runs in linear time and is safe for any string key.
Show answer
items.reduce((g, i) => { (g[i.type] ??= []).push(i); return g; }, Object.create(null)). It mutates a single accumulator instead of copying it on every step, and the null-prototype initial value avoids collisions with inherited keys.