map / filter / reduce

These three array methods are the foundation of functional programming in JavaScript.

map — transform each element

const nums = [1, 2, 3, 4, 5]

const doubled = nums.map(n => n * 2)
// [2, 4, 6, 8, 10]

const names = ['alice', 'bob', 'carol']
const upper = names.map(name => name.toUpperCase())
// ['ALICE', 'BOB', 'CAROL']

filter — keep elements that pass a test

const nums = [1, 2, 3, 4, 5, 6]

const evens = nums.filter(n => n % 2 === 0)
// [2, 4, 6]

const words = ['hello', 'hi', 'hey', 'world']
const h = words.filter(w => w.startsWith('h'))
// ['hello', 'hi', 'hey']

reduce — accumulate to a single value

const nums = [1, 2, 3, 4, 5]

const sum = nums.reduce((total, n) => total + n, 0)
// 15

const product = nums.reduce((acc, n) => acc * n, 1)
// 120

Chaining

const result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  .filter(n => n % 2 === 0)   // [2, 4, 6, 8, 10]
  .map(n => n * n)             // [4, 16, 36, 64, 100]
  .reduce((sum, n) => sum + n, 0) // 220

console.log(result) // 220