stackademic

The leading education platform for anyone with an interest in software development.

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 map for side effects—use forEach instead (or a for loop)
  • Forgetting the initial value in reduce when the accumulator type matters
  • Chaining sort without copy—[...arr].sort() avoids mutation
  • Assuming find returns boolean—it returns the element or undefined

See Also

arrays functions spread-rest promises