Arrays and objects
map, filter and reduce
Goal: Transform, select and aggregate array data · 12 min
Three methods replace most loops over arrays:
- map(f) — a new array with f applied to every element:
[1, 2, 3].map(x => x * 2)→ [2, 4, 6] - filter(test) — a new array with only the elements where test is true:
[1, 2, 3, 4].filter(x => x % 2 === 0)→ [2, 4] - reduce((acc, x) => …, start) — combines all elements into one value:
[1, 2, 3].reduce((s, x) => s + x, 0)→ 6
They do not change the original array and can be chained: orders.filter(o => o.paid).map(o => o.total).reduce((a, b) => a + b, 0). Related: find, some, every.
Worked example: Revenue from paid orders
- filter keeps paid orders.
- map extracts the totals: [20, 15].
- reduce adds them: 35.
const orders = [{ total: 20, paid: true }, { total: 50, paid: false }, { total: 15, paid: true }];
const revenue = orders.filter(o => o.paid).map(o => o.total).reduce((a, b) => a + b, 0);
console.log(revenue);Output:
35