Sub topic 9
Reduce Patterns: Grouping, Counting, and Indexing
This chapter assumes you already know how reduce walks an array with an accumulator, and why you pass an initial value. Here the initial value is an empty object or a Map, and the result is a lookup structure instead of a number. Three patterns cover most of the work: counting, grouping, and indexing. They all follow the same recipe:
- Start with an empty container.
- For each element, compute a key.
- Update the container at that key.
- Return the container so the next step receives it.
The only thing that changes from pattern to pattern is what step 3 stores.
The Shared Shape
Each pattern below follows this template:
const result = items.reduce((acc, item) => {
const key = computeKey(item);
// update acc[key] somehow
return acc;
}, {});The return acc line is required. If you forget it, the callback returns undefined, and the next iteration fails with something like TypeError: Cannot read properties of undefined. This is the most common reduce bug in real code.
Counting: Frequency Tables
Counting stores a number at each key. You read the current count (or 0 if the key is missing), add one, and write it back.
const votes = ['red', 'blue', 'red', 'green', 'red', 'blue'];
const tally = votes.reduce((counts, color) => {
counts[color] = (counts[color] ?? 0) + 1;
return counts;
}, {});
console.log(tally); // { red: 3, blue: 2, green: 1 }?? 0 handles the first time a key appears, when counts[color] is undefined. Don't use || 0 here. It happens to work for counts, but the habit breaks the moment a stored value can legitimately be 0 or ''.
The key can be computed from the element. It doesn't have to be the element itself. For example, you can count words by length:
const words = ['map', 'filter', 'reduce', 'find', 'some'];
const byLength = words.reduce((counts, word) => {
const len = word.length;
counts[len] = (counts[len] ?? 0) + 1;
return counts;
}, {});
console.log(byLength); // { '3': 1, '4': 2, '6': 2 }The keys in that result are strings. Plain objects convert every property key to a string (symbols are the only exception), so 3 becomes '3'. If you need the numeric keys to stay numbers, use a Map, covered below.
Grouping: Buckets of Elements
Grouping stores an array at each key and pushes the element into it. The logical nullish assignment operator ??= creates the array the first time a key appears:
const people = [
{ name: 'Ada', team: 'compilers' },
{ name: 'Grace', team: 'compilers' },
{ name: 'Linus', team: 'kernel' }
];
const byTeam = people.reduce((groups, person) => {
(groups[person.team] ??= []).push(person.name);
return groups;
}, {});
console.log(byTeam);
// { compilers: ['Ada', 'Grace'], kernel: ['Linus'] }groups[key] ??= [] evaluates to the array stored at that key, either the existing one or the one it just created. That's why you can call .push on it directly. The example pushes person.name rather than person. Store whatever shape the consumer needs.
Partitioning: Grouping into Exactly Two Buckets
When the key is a boolean, grouping becomes partitioning. A fixed initial shape is clearer here than dynamic keys:
const scores = [42, 91, 67, 88, 55];
const { pass, fail } = scores.reduce(
(acc, score) => {
acc[score >= 60 ? 'pass' : 'fail'].push(score);
return acc;
},
{ pass: [], fail: [] }
);
console.log(pass); // [91, 67, 88]
console.log(fail); // [42, 55]The alternative is two filter calls. That reads well too, but it walks the array twice and evaluates the predicate twice per element. With a cheap predicate and a small array, either version is fine.
Indexing: Lookup by ID
Indexing stores one element per key. Usually you index records by a unique ID so you can find a record in constant time instead of calling find over and over.
const products = [
{ id: 'p1', name: 'Keyboard', price: 49 },
{ id: 'p2', name: 'Mouse', price: 19 },
{ id: 'p3', name: 'Monitor', price: 199 }
];
const productsById = products.reduce((index, product) => {
index[product.id] = product;
return index;
}, {});
const cart = ['p3', 'p2', 'p3'];
const cartTotal = cart.reduce((sum, id) => sum + productsById[id].price, 0);
console.log(productsById.p2.name); // 'Mouse'
console.log(cartTotal); // 417Without the index, each lookup in the cart would be a linear find. That makes the total O(cart × products). With the index, it's O(cart + products).
Duplicate Keys
Indexing assumes keys are unique. If two records share an ID, the last one silently overwrites the first. When the data comes from outside your code, check for duplicates explicitly:
const rows = [
{ id: 1, v: 'a' },
{ id: 2, v: 'b' },
{ id: 1, v: 'c' }
];
try {
rows.reduce((index, row) => {
if (row.id in index) {
throw new Error(`Duplicate id: ${row.id}`);
}
index[row.id] = row;
return index;
}, {});
} catch (err) {
console.log(err.message); // 'Duplicate id: 1'
}Using a Map as the Accumulator
A Map is often the better container than a plain object:
| Concern | Plain object `{}` | `Map` |
|---|---|---|
| Key types | Strings and symbols only; numbers become strings | Any value, including objects and numbers |
| Inherited keys | `constructor`, `toString`, and others already exist | None |
| Insertion order | Integer-like keys are sorted first | Always insertion order |
| JSON output | `JSON.stringify` works directly | Convert first with `Object.fromEntries` |
| Size | `Object.keys(obj).length` | `map.size` |
Map.prototype.set returns the map itself, so a counting reducer fits on one line:
const readings = [3, 1, 3, 2, 3, 1];
const freq = readings.reduce(
(m, n) => m.set(n, (m.get(n) ?? 0) + 1),
new Map()
);
console.log(freq); // Map(3) { 3 => 3, 1 => 2, 2 => 1 }
console.log(freq.get(3)); // 3 (a number key, not '3')
console.log(Object.fromEntries(freq)); // { '1': 2, '2': 1, '3': 3 }The Inherited-Key Trap
This trap is why the table recommends Map when keys come from user data. A plain {} inherits properties from Object.prototype:
const tokens = ['constructor', 'map', 'constructor'];
const broken = tokens.reduce((counts, t) => {
counts[t] = (counts[t] ?? 0) + 1;
return counts;
}, {});
console.log(typeof broken.constructor); // 'string' (garbage)
const safe = tokens.reduce((counts, t) => {
counts[t] = (counts[t] ?? 0) + 1;
return counts;
}, Object.create(null));
console.log(safe.constructor); // 2In the broken version, counts.constructor starts as the Object function, not undefined. The ?? 0 never kicks in, and Object + 1 turns into a string. The key __proto__ is worse: assigning to it changes the object's prototype instead of storing a value. If you must use an object, use Object.create(null) as the initial value. Otherwise use a Map.
Mutating the Accumulator Is Fine. Spreading It Is Slow.
Earlier chapters stressed not mutating your inputs. The accumulator is different. Your reducer created it, nothing else holds a reference to it, and it never escapes until reduce finishes. Mutating it is safe.
Some code tries to stay "pure" by copying the accumulator on every step:
const letters = ['x', 'y', 'x'];
// Works, but copies the whole object on every iteration: O(n²)
const slow = letters.reduce(
(acc, l) => ({ ...acc, [l]: (acc[l] ?? 0) + 1 }),
{}
);
console.log(slow); // { x: 2, y: 1 }Each spread copies every key collected so far. With n distinct keys, that's about n²/2 property copies in total. For a few thousand distinct keys, this version is visibly slower than mutating in place. Keep the elements you're reducing immutable, and let the accumulator be mutable.
Built-in Alternatives: Object.groupBy and Map.groupBy
ES2024 added built-in grouping functions. They are available in Node.js 21+ and current browsers.
const inventory = [
{ name: 'apple', type: 'fruit' },
{ name: 'leek', type: 'vegetable' },
{ name: 'pear', type: 'fruit' }
];
const grouped = Object.groupBy(inventory, item => item.type);
console.log(grouped.fruit.map(i => i.name)); // ['apple', 'pear']
const grouped2 = Map.groupBy(inventory, item => item.type);
console.log(grouped2.get('vegetable').length); // 1Object.groupBy returns a null-prototype object, so the inherited-key trap doesn't apply. Use these functions when you need plain grouping and your target runtimes support them. Reach for reduce when you need to count, index, transform values while grouping, or detect duplicates. Those are cases the built-ins don't cover.
Exercise
Given const orders = [{ customer: 'ana', total: 30 }, { customer: 'ben', total: 15 }, { customer: 'ana', total: 25 }], write a single reduce call that produces { ana: 55, ben: 15 }, the total spent per customer.
Show answer
orders.reduce((acc, o) => { acc[o.customer] = (acc[o.customer] ?? 0) + o.total; return acc; }, {}). This is the counting pattern, adding o.total instead of 1. The ?? 0 provides the starting amount the first time a customer appears, and returning acc hands the object to the next iteration.
Exercise
A teammate counts tags from user input with tags.reduce((c, t) => { c[t] = (c[t] ?? 0) + 1; return c; }, {}). A user submits the tag "toString", and the result for that tag is a long string instead of a number. Explain why, and give two fixes.
Show answer
The empty object inherits toString from Object.prototype, so c['toString'] is a function, not undefined. The ?? 0 fallback never applies, and adding 1 to the function concatenates its source text with '1'. Fix it by using Object.create(null) as the initial value, or by using a Map: tags.reduce((m, t) => m.set(t, (m.get(t) ?? 0) + 1), new Map()).
Exercise
Why is (acc, x) => ({ ...acc, [x.id]: x }) a poor reducer for indexing 50,000 records, and what should you write instead?
Show answer
Each iteration copies every key collected so far into a new object, so the total work grows quadratically, roughly n²/2 property copies. The accumulator is private to the reduce call, so mutating it is safe: (acc, x) => { acc[x.id] = x; return acc; } does the same job in linear time.