Sub topic 3
Reduce Patterns, Pitfalls, and Beyond the Big Three
This chapter assumes you already know map, filter, reduce, initial values, and chaining. It also assumes you are familiar with Promises and async/await.
Reduce Patterns: Grouping, Counting, and Indexing
If you start reduce with {}, it can build a lookup structure instead of a single number. The callback must return the accumulator on every call.
const words = ['apple', 'banana', 'avocado', 'apple'];
const groups = words.reduce((acc, w) => {
(acc[w[0]] ??= []).push(w);
return acc;
}, {});
const counts = words.reduce((acc, w) => {
acc[w] = (acc[w] ?? 0) + 1;
return acc;
}, {});
const users = [{ id: 7, name: 'Ada' }, { id: 9, name: 'Linus' }];
const byId = users.reduce((acc, u) => ({ ...acc, [u.id]: u }), {});
console.log(groups); // { a: ['apple', 'avocado', 'apple'], b: ['banana'] }
console.log(counts); // { apple: 2, banana: 1, avocado: 1 }
console.log(byId[9].name); // 'Linus'Common Pitfalls
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]
const users = [{ name: 'Ada', active: false }];
const activated = users.map(u => ({ ...u, active: true })); // copy, don't mutate
console.log(users[0].active, activated[0].active); // false true
console.log([1, , 3].map(x => x * 2)); // [2, <1 empty item>, 6]mappasses(element, index, array)to the callback.parseIntreads the index as its radix, which produces theNaNvalues above.mapreturns a new array, but the objects inside it are still shared with the original. Copy each object before you change it.- Sparse arrays have holes.
map,filter, andreduceskip the holes and never call the callback for them.
Applying Them to Objects
const prices = { apple: 1, pear: 2, mango: 3 };
const doubled = Object.fromEntries(
Object.entries(prices)
.filter(([, p]) => p > 1)
.map(([k, p]) => [k, p * 2])
);
console.log(doubled); // { pear: 4, mango: 6 }Async Callbacks
An async callback always returns a promise. That means map gives you an array of promises, and Promise.all turns it into an array of values. Run the example below as an ES module so that top-level await works.
const delay = ms => new Promise(r => setTimeout(r, ms));
const results = await Promise.all([1, 2, 3].map(async n => {
await delay(10);
return n * 2;
}));
console.log(results); // [2, 4, 6]Don't pass an async callback to reduce or filter. With filter, the callback returns a promise, which is always truthy, so every element is kept.
Beyond the Big Three
| Method | Use when | Stops early? |
|---|---|---|
| `flatMap` | Each element maps to zero or more items | No |
| `find` | You need the first match | Yes |
| `some` / `every` | You need a boolean | Yes |
| `reduceRight` | Order matters from the end | No |
Readability Versus Performance
A chain of methods allocates a new intermediate array at every step, and it cannot break out early. Use a for...of loop when you need any of these:
- a hot path over very large arrays
- early exit, where
findorsomedon't fit awaitin sequence, one item after another
For everything else, readability usually matters more than the extra arrays.
Exercise
Why does [3, 8, 12].filter(async n => n > 5) return all three elements?
Show answer
An async callback returns a Promise, and every Promise object is truthy, so filter keeps every element. Resolve the conditions first with Promise.all, then filter with the resolved booleans.
Exercise
Write a reduce call that counts how many orders exist per status in [{status:'paid'},{status:'pending'},{status:'paid'}].
Show answer
orders.reduce((acc, o) => { acc[o.status] = (acc[o.status] ?? 0) + 1; return acc; }, {}) returns { paid: 2, pending: 1 }.