When would you choose map, filter, and reduce?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
map transforms every item into a new array of the same length, filter keeps items matching a predicate, and reduce folds everything into a single value — sum, object, anything.
Detailed explanation
These three cover most array processing. map answers 'transform each element': same length in and out. filter answers 'which elements do I keep?': length shrinks, elements unchanged. reduce is the general-purpose folder: it accumulates a result across iterations — numbers (totals), objects (grouping/counting), even new arrays when chaining feels wasteful. They're chainable because each returns a fresh array/value, leaving the original untouched — important for predictable code and immutable state updates. Performance note: many chained passes can be merged into one reduce if profiling shows it matters, but clarity wins by default. Knowing forEach exists too helps articulate the difference: forEach returns undefined and is for side effects, not transformation.
Example
const orders = [
{ id: 1, total: 120, status: 'paid' },
{ id: 2, total: 80, status: 'pending' },
{ id: 3, total: 45, status: 'paid' },
];
orders.filter(o => o.status === 'paid')
.map(o => o.total)
.reduce((sum, t) => sum + t, 0); // 165
// reduce building an object:
orders.reduce((acc, o) => {
acc[o.status] = (acc[o.status] ?? 0) + 1;
return acc;
}, {}); // { paid: 2, pending: 1 }Interview tip
Anchor each method to one verb — transform, select, fold — then run a realistic pipeline. Mentioning forEach's side-effect-only role shows completeness.
Common mistakes
- Using map for side effects instead of forEach.
- Forgetting the initial value argument of reduce, causing crashes on empty arrays.