JavaScript Tutorial · Objects and Arrays · Lesson 24 of 44

JavaScript Array Methods

Transform data with map, filter, reduce, some, every and flat.

map, filter and reduce

These three methods are the heart of everyday JavaScript data work. They don't change the original array.

  • map(fn) — transform every item into a new array.
  • filter(fn) — keep the items where fn returns true.
  • reduce(fn, start) — combine all items into one value.
Example 1Try it yourself
const nums = [1, 2, 3, 4, 5];
console.log(nums.map((n) => n * n));
console.log(nums.filter((n) => n % 2 === 0));
console.log(nums.reduce((total, n) => total + n, 0));

Output

[ 1, 4, 9, 16, 25 ]
[ 2, 4 ]
15

Chaining

Because they return arrays, you can chain them into readable pipelines:

Example 2Try it yourself
const orders = [
  { item: "book", price: 12, qty: 2 },
  { item: "pen", price: 1.5, qty: 10 },
  { item: "bag", price: 40, qty: 0 },
];
const revenue = orders
  .filter((o) => o.qty > 0)
  .map((o) => o.price * o.qty)
  .reduce((sum, value) => sum + value, 0);
console.log(revenue);

Output

39

some, every, forEach and flat

Example 3Try it yourself
const ages = [19, 24, 31];
console.log(ages.some((a) => a > 30));
console.log(ages.every((a) => a >= 18));
ages.forEach((age, i) => console.log(i, age));
console.log([[1, 2], [3, [4]]].flat(2));
console.log(["a b", "c"].flatMap((s) => s.split(" ")));

Output

true
true
0 19
1 24
2 31
[ 1, 2, 3, 4 ]
[ 'a', 'b', 'c' ]

Grouping

Object.groupBy() (ES2024) groups items by a key:

Example 4Try it yourself
const people = [
  { name: "Ada", team: "core" },
  { name: "Lin", team: "web" },
  { name: "Sam", team: "core" },
];
const byTeam = Object.groupBy(people, (p) => p.team);
console.log(Object.keys(byTeam));
console.log(byTeam.core.map((p) => p.name));

Output

[ 'core', 'web' ]
[ 'Ada', 'Sam' ]

Test yourself

Which method returns a new array containing only the items that pass a test?

  1. map()
  2. filter()
  3. reduce()
  4. forEach()
Show answer

Answer: filter()

Practice next