Prompt
Given const numbers = [1, 2, 3, 4, 5, 6, 7], chain map, filter, and reduce to:
- Double each number (map)
- Keep only numbers > 5 (filter)
- Sum the result (reduce)
Assign the answer to
const result.
Solution
The chain works because map and filter each return a new array without touching the source — that non-mutation is what makes the pipeline composable and is the same contract React state updates depend on. Each stage does one thing: transform, select, aggregate. A reviewer can verify each line independently, which is the honest argument for this style over a hand-rolled loop that interleaves all three concerns.
Trace it, because interviewers make you: doubling gives [2,4,6,8,10,12,14]; filtering > 5 keeps [6,8,10,12,14] — note 6 and 14 both survive, the two values people drop — and the sum is 50. The reduce initial value 0 matters twice: it makes an empty filtered result return 0 instead of throwing, and it makes the accumulator's type explicit.
Know the cost you're paying: three passes and two intermediate arrays. For UI-sized data that's noise; in a hot path over large data (a React Native list transform running per render), collapsing into a single reduce — or better, memoizing so it doesn't rerun at all — is the senior answer. Say the trade-off before the interviewer asks.
Red flag: omitting reduce's initial value. It "works" on this array by using the first element as the seed, but it throws on an empty array and skips your callback for index 0 — a latent production bug that passes the happy-path test.
Say it: "map and filter return new arrays, so the chain is pure and composable — I pay two intermediate allocations for readability, and I collapse to a single pass only when profiling says it matters."