Array Methods
Transform data with map, filter, reduce, find, and more
Overview
Array prototype methods express common transformations declaratively. Most return new arrays (non-mutating); sort, reverse, splice mutate in place. Chain methods for readable pipelines.
Syntax / Usage
const nums = [1, 2, 3, 4, 5]
nums.map((n) => n * 2) // [2, 4, 6, 8, 10]
nums.filter((n) => n % 2 === 0) // [2, 4]
nums.find((n) => n > 3) // 4
nums.findIndex((n) => n > 3) // 3
nums.some((n) => n > 4) // true
nums.every((n) => n > 0) // true
nums.reduce((sum, n) => sum + n, 0) // 15
nums.includes(3) // true
nums.flatMap((n) => [n, n]) // [1,1,2,2,...]
Examples
Pipeline: filter, map, sort:
const products = [
{ name: 'Keyboard', price: 79, inStock: true },
{ name: 'Mouse', price: 49, inStock: false },
]
const catalog = products
.filter((p) => p.inStock)
.map((p) => ({ ...p, label: `${p.name} — $${p.price}` }))
.sort((a, b) => a.price - b.price)
Group items by category:
const items = [
{ cat: 'fruit', name: 'apple' },
{ cat: 'fruit', name: 'banana' },
{ cat: 'veg', name: 'carrot' },
]
const grouped = items.reduce((acc, item) => {
acc[item.cat] = acc[item.cat] || []
acc[item.cat].push(item.name)
return acc
}, {})
Common Mistakes
- Using
mapfor side effects—useforEachinstead (or aforloop) - Forgetting the initial value in
reducewhen the accumulator type matters - Chaining
sortwithout copy—[...arr].sort()avoids mutation - Assuming
findreturns boolean—it returns the element orundefined
See Also
arrays functions spread-rest promises