JavaScript Array Iteration

map, filter, reduce — Transform, Pick, Combine

JavaScript Array Iteration

The four array methods you'll use every day — `map`, `filter`, `reduce`, `forEach`. Plus `find` and `some` / `every`.

7 min read Level 2/5 #arrays#map#filter
What you'll learn
  • Transform every item with `map`
  • Pick items that match a condition with `filter`
  • Combine items into a single result with `reduce`
  • Choose the right one for the job

Four methods that transform the way you work with arrays. Each takes a callback function that runs on every item.

map — transform every item

map runs your function on each item and returns a new array of the results. Same length, possibly different values.

Double every number script.js
const numbers = [1, 2, 3, 4];

const doubled = numbers.map((n) => n * 2);
console.log(doubled);  // [2, 4, 6, 8]
console.log(numbers);  // [1, 2, 3, 4] (unchanged)
▶ Preview: console
Map over objects script.js
const users = [
  { name: "Ada", age: 36 },
  { name: "Lin", age: 28 },
];

const names = users.map((u) => u.name);
console.log(names); // ["Ada", "Lin"]
▶ Preview: console

filter — pick the ones that match

filter runs a predicate (a function that returns true/false) and returns a new array of items where it returned true.

Keep even numbers script.js
const numbers = [1, 2, 3, 4, 5, 6];

const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens);   // [2, 4, 6]
▶ Preview: console
Adults only script.js
const users = [
  { name: "Ada", age: 36 },
  { name: "Tim", age: 12 },
  { name: "Lin", age: 28 },
];

const adults = users.filter((u) => u.age >= 18);
console.log(adults);
// [{name: "Ada", age: 36}, {name: "Lin", age: 28}]
▶ Preview: console

reduce — combine into a single value

reduce walks through the array carrying an “accumulator” value, letting you decide what to do with each item.

Sum a list of numbers script.js
const prices = [10, 15, 20];

const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 45
▶ Preview: console

The 0 at the end is the starting value of the accumulator. The callback receives (accumulator, currentItem) and returns the new accumulator.

Group by a property script.js
const orders = [
  { user: "Ada", amount: 10 },
  { user: "Lin", amount: 20 },
  { user: "Ada", amount: 5 },
];

const totalsByUser = orders.reduce((acc, order) => {
  acc[order.user] = (acc[order.user] ?? 0) + order.amount;
  return acc;
}, {});

console.log(totalsByUser);  // { Ada: 15, Lin: 20 }
▶ Preview: console

forEach — just run something on each

forEach runs your callback on every item and returns undefined. Use it when you want a side effect, not a transformed result.

forEach for side effects script.js
const fruits = ["apple", "banana", "grape"];

fruits.forEach((fruit) => {
  console.log(`I like ${fruit}!`);
});
▶ Preview: console

find — first match

Returns the first item that passes the predicate, or undefined if nothing matches.

find script.js
const users = [
  { id: 1, name: "Ada" },
  { id: 2, name: "Lin" },
];

const user = users.find((u) => u.id === 2);
console.log(user); // { id: 2, name: "Lin" }

const missing = users.find((u) => u.id === 99);
console.log(missing); // undefined
▶ Preview: console

some / every — quick yes/no on the whole array

some and every script.js
const ages = [12, 19, 21, 30];

console.log(ages.some((a) => a >= 18));   // true   — at least one adult
console.log(ages.every((a) => a >= 18));  // false  — not all are adults

console.log(ages.every((a) => a > 0));    // true   — all positive
▶ Preview: console

Picking the Right One

You want…Use
A new array, same lengthmap
A new array, fewer itemsfilter
A single value (sum, max, group)reduce
Just to do something on eachforEach
The first matching itemfind
Yes/no: any match?some
Yes/no: all match?every

You can also chain them — each returns a new array, so you can chain filter().map() for “pick some, then transform them”:

Chain filter + map script.js
const orders = [
  { user: "Ada", amount: 10, paid: true },
  { user: "Lin", amount: 20, paid: false },
  { user: "Tim", amount: 30, paid: true },
];

const paidUsers = orders
  .filter((o) => o.paid)
  .map((o) => o.user);

console.log(paidUsers); // ["Ada", "Tim"]
▶ Preview: console

Try It Yourself

Exercise

Sum a shopping cart

Difficulty 2/5~3 min
Given the `cart` array of items below, compute a constant `total` that is the sum of all item prices using `reduce`. Log it. The expected output is `45`.
solution.js
const cart = [
  { name: "apple", price: 10 },
  { name: "bread", price: 15 },
  { name: "cheese", price: 20 },
];
// your code here
2tests will run
💡 Show hint
`cart.reduce((sum, item) => sum + item.price, 0)`. Start with `0` as the initial accumulator.
✅ Show solution
const cart = [
  { name: "apple", price: 10 },
  { name: "bread", price: 15 },
  { name: "cheese", price: 20 },
];
const total = cart.reduce((sum, item) => sum + item.price, 0);
console.log(total);

Up Next

Destructuring — a cleaner way to pull items out of an array.

JavaScript Array Destructuring →