Sub topic 9
Reduce Patterns: Grouping, Counting, and Indexing
This chapter assumes you know how reduce passes an accumulator from one call to the next, and why you should pass an initial value. In this chapter that initial value will be an empty object {} or an empty Map, so reduce builds a lookup structure instead of a number.
Grouping, counting, and indexing all have the same shape. You start with an empty container. Each callback reads one element, computes a key, updates the container at that key, and returns the container.
Counting Occurrences
Counting is the simplest version. The key is the element, and the value is how many times that element has appeared.
const votes = ['yes', 'no', 'yes', 'yes', 'no', 'abstain'];
const tally = votes.reduce((counts, vote) => {
counts[vote] = (counts[vote] ?? 0) + 1;
return counts;
}, {});
console.log(tally); // { yes: 3, no: 2, abstain: 1 }The ?? 0 handles the first time a key appears. At that point counts[vote] is undefined, and undefined + 1 would give NaN.
Grouping Elements by a Key
Grouping stores an array for each key instead of a number. The callback picks the key and pushes the element into that key's array, creating the array the first time the key appears.
const words = ['apple', 'banana', 'avocado', 'cherry'];
const byFirstLetter = words.reduce((groups, word) => {
const key = word[0];
(groups[key] ??= []).push(word);
return groups;
}, {});
console.log(byFirstLetter);
// { a: ['apple', 'avocado'], b: ['banana'], c: ['cherry'] }The ??= operator assigns [] only when groups[key] is null or undefined, and the expression evaluates to the array. That lets you push in the same statement.
Modern runtimes (Node 21+ and current browsers) also provide Object.groupBy(words, w => w[0]), which gives the same result. It returns an object with a null prototype, so methods like hasOwnProperty are not available on it. Use the reduce version when you need to support older runtimes or want to transform each element as you group it.
Indexing Records by ID
Indexing turns an array into a lookup table, so you can find a record by key in constant time instead of calling find repeatedly.
const users = [
{ id: 'u1', name: 'Ada' },
{ id: 'u2', name: 'Grace' },
{ id: 'u3', name: 'Linus' }
];
const usersById = users.reduce((index, user) => {
index[user.id] = user;
return index;
}, {});
console.log(usersById.u2.name); // 'Grace'If two records share an ID, the later one silently overwrites the earlier one. Check for that case if duplicate IDs would mean bad data.
Using a Map as the Accumulator
Plain objects convert every key to a string, so the number 5 and the string '5' end up as the same key. A Map keeps keys at their original type and remembers insertion order. Map.prototype.set returns the map, so the callback can be a single expression:
const fruits = ['fig', 'kiwi', 'pear', 'plum', 'banana'];
const countByLength = fruits.reduce(
(counts, fruit) => counts.set(fruit.length, (counts.get(fruit.length) ?? 0) + 1),
new Map()
);
console.log(countByLength); // Map(3) { 3 => 1, 4 => 3, 6 => 1 }
console.log(countByLength.get(4)); // 3Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `return acc` in a block body | `TypeError` on the second element, because the accumulator is `undefined` | Always return the accumulator |
| Omitting the initial `{}` | The first element becomes the accumulator | Pass `{}` or `new Map()` |
| Writing `({ ...acc, [key]: value })` each step | Correct output, but quadratic time on large arrays | Mutate the accumulator you created |
Exercise
Given const emails = ['[email protected]', '[email protected]', '[email protected]'], write a reduce call that counts addresses per domain and returns { 'x.com': 2, 'y.com': 1 }.
Show answer
emails.reduce((counts, email) => { const domain = email.split('@')[1]; counts[domain] = (counts[domain] ?? 0) + 1; return counts; }, {})
Exercise
Why would you use new Map() instead of {} as the initial value when grouping orders by a numeric customerId?
Show answer
An object coerces the numeric keys to strings, so you get string keys back. A Map keeps the numbers as numbers, so map.get(42) works without conversion, and it also preserves insertion order for every key type.