JavaScript From Zero · 20 min · 150 XP

map, filter, reduce

Answer questions about data with map, filter and reduce, and chain them into readable pipelines.

Most everyday data work is three moves. filter keeps the items that pass a test. map turns each item into something else. reduce folds the whole list into one value: a total, a count, an object of groups. Each returns something new and leaves the original array alone.

javascript
const paid = orders.filter((o) => o.status === "paid");
const totals = paid.map((o) => o.total);
const revenue = totals.reduce((sum, t) => sum + t, 0);

// or as one pipeline
const revenue2 = orders
  .filter((o) => o.status === "paid")
  .reduce((sum, o) => sum + o.total, 0);

Always give reduce a starting value (the 0 above). Without one, reduce starts from the first item, which breaks when the items are objects, and it throws on an empty array: the day there are no orders, the page crashes. Relatives worth knowing: find (the first match), some and every (true/false answers), and includes.

reduce into an object: totals per group
const byCategory = paid.reduce((acc, o) => {
  acc[o.category] = (acc[o.category] ?? 0) + o.total;
  return acc;
}, {});

Loading your workspace…