Array Methods Deep Dive
map, filter, reduce, chaining, immutability
What you'll learn
Use map, filter, reduce, find, some, every, flat, flatMap
Chain methods for readable pipelines
Understand mutable vs immutable
Use reduce as multi-purpose tool
Core Methods
const n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n.map((x) => x * 2) // [2, 4, 6, ... 20] — transform each
n.filter((x) => x % 2 === 0) // [2, 4, 6, 8, 10] — keep matches
n.find((x) => x > 5) // 6 — first match
n.some((x) => x % 2 === 0) // true — any match?
n.every((x) => x > 0) // true — all match?
reduce
;[1, 2, 3, 4, 5]
.reduce((a, n) => a + n, 0) // 15 — sum
[(1, 2, 3)].reduce((a, n) => [...a, n * 2], []) // [2, 4, 6] — map
[(1, 2, 3)].reduce((a, n) => (n % 2 ? a : [...a, n]), []) // [2] — filter
[
// Group objects by property
({ name: "A", r: "admin" }, { name: "B", r: "editor" })
].reduce((a, p) => ((a[p.r] ??= []).push(p), a), {})
flat & flatMap
;[1, [2, [3]]]
.flat() // [1, 2, [3]]
[(1, [2, [3]])].flat(Infinity) // [1, 2, 3]
["hello world"].flatMap((s) => s.split(" ")) // ["hello", "world"]
[(1, -2, 3)].flatMap((n) => (n > 0 ? [n * 2] : [])) // [2, 6] — map + filter
Method Chaining
Performance
Chaining creates intermediate arrays. Fine for
<10K items. For huge data use single-pass reduce.Immutable vs Mutable
[3, 1, 2].sort() // [1, 2, 3] — mutates!
[...[3, 1, 2]].sort() // safe copy
[3, 1, 2].toSorted() // ES2023 — immutable
Gotcha
sort() defaults to string sort: [1, 10, 2].sort() → [1, 10, 2]. Always pass (a, b) => a - b. Also mutates — copy first.See It In Action
Data Pipeline
Code
javascript
1const tx = [2{ id:1, amount:100, currency:"USD", category:"food", status:"completed" },3{ id:2, amount:50, currency:"EUR", category:"transport", status:"completed" },4{ id:3, amount:200, currency:"USD", category:"food", status:"pending" },5]6 7function processTransactions(txns, rate = 0.92) {8return txns9.filter(t => t.status === "completed")10.map(t => ({11...t,12totalEUR: t.currency === "USD" ? t.amount * rate : t.amount,13}))14.reduce((acc, t) => {15acc[t.category] = (acc[t.category] || 0) + t.totalEUR16return acc17}, {} as Record<string, number>)18}19 20console.log(processTransactions(tx))21// { food: 276, transport: 46 }A data pipeline chains `filter`, `map`, and `reduce` to process transactions: filter only completed ones, convert USD to EUR, then group by category and sum amounts.
Lesson Summary
Key Takeaways
map (transform), filter (keep), find (first), reduce (swiss army knife)
flatMap maps + flattens one level; flat flattens arbitrary depth
Chain methods for declarative data pipelines
sort mutates — use toSorted() or copy; always pass comparator