ILILCode
HomeJavaScriptFunctions & data

Array methods: map, filter, reduce and friends

Stop writing loops by hand. Transform, select and collapse arrays with intent.

Lesson 9 of 23 in JavaScript12 min1 exercise

These methods take a callback and run it for each item. Learn them and half your loops disappear.

The core three
const nums = [1, 2, 3, 4];

nums.map((n) => n * 2);       // [2, 4, 6, 8]  transform each item
nums.filter((n) => n % 2 === 0); // [2, 4]     keep matching items
nums.reduce((sum, n) => sum + n, 0); // 10     collapse to one value
Finding, testing, sorting
const people = [
  { name: "Ada", age: 36 },
  { name: "Alan", age: 41 },
  { name: "Grace", age: 85 },
];

people.find((p) => p.age > 40);   // { name: "Alan", ... } (first match)
people.findIndex((p) => p.age > 40); // 1
people.some((p) => p.age > 80);   // true  (at least one)
people.every((p) => p.age > 18);  // true  (all)

const names = people.map((p) => p.name);
names.sort();                     // ["Ada", "Alan", "Grace"]

const byAge = [...people].sort((a, b) => a.age - b.age); // copy first!

Methods chain because each returns a new array. A read-only chain like filter then map is often clearer than one clever reduce.

Chaining
const orders = [
  { item: "keyboard", price: 80, qty: 2 },
  { item: "mouse", price: 25, qty: 1 },
  { item: "monitor", price: 300, qty: 1 },
];

const total = orders.reduce((sum, o) => sum + o.price * o.qty, 0);
const bigItems = orders.filter((o) => o.price > 50).map((o) => o.item);
// total = 485, bigItems = ["keyboard", "monitor"]

Try it

The same data, four ways

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Summarise a list of orders

Write report(orders) that returns an object with three properties:

  • count — how many orders there are
  • revenue — the total of price * qty across all orders
  • top — the item name with the highest price * qty, or null when there are no orders (first wins on a tie)

Use reduce at least once.

exercise.js
console · run your code or check the answer