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 wherefnreturns true.reduce(fn, start)— combine all items into one value.
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:
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
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:
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?
map()filter()reduce()forEach()
Show answer
Answer: filter()
Practice next
- Group Anagrams · coding problem
- Type-safe groupBy<T, K>() · coding problem