These methods take a function and apply it to the array elements. They return a new array (or value) without themselves replacing the original items. The function you pass in can still change the original array or its objects:
map makes a new array by changing every element.
filter keeps only the elements for which the function returns true.
reduce combines all the elements into one value, such as a total.
const prices = [4, 10, 25];
const withTax = prices.map((p) => p * 1.1);
console.log(withTax.map((p) => p.toFixed(2))); // ["4.40","11.00","27.50"]
const cheap = prices.filter((p) => p < 20);
console.log(cheap); // [4,10]
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total); // 39
In reduce, sum is the accumulator 累加器. It starts at the last argument (0) and takes the function's result after each element. For [3, 8, 5].reduce((sum, n) => sum + n, 0):
Element n |
sum before |
sum + n (the new sum) |
| 3 |
0 |
3 |
| 8 |
3 |
11 |
| 5 |
11 |
16 |
The result is the last sum, 16.
You can chain 链式调用 these methods: each one works on the array that the one before it returned. Read the chain from left to right:
const scores = [55, 82, 47, 91, 68];
const passed = scores
.filter((s) => s >= 50) // [55,82,91,68]
.map((s) => s + 5); // add 5 bonus points
console.log(passed); // [60,87,96,73]
Practice
Each task has one line of work: choose map, filter or reduce. Write it on paper first,
then open the model answer, compare, and press Run.
1. Prices with tax. const prices = [10, 25, 4]; Make a new array with 20% tax added to
each price.
Model answer
const prices = [10, 25, 4];
const withTax = prices.map((p) => p * 1.2);
console.log(withTax); // [12,30,4.8]
map: one new value for each old one, so the new array has the same length.
2. Names that start with A. const names = ["Ana", "Ben", "Aisha", "Carl"]; Keep only
the names that start with "A".
Model answer
const names = ["Ana", "Ben", "Aisha", "Carl"];
const aNames = names.filter((n) => n.startsWith("A"));
console.log(aNames); // ["Ana","Aisha"]
filter: the function answers yes or no for each item, and only the yes items are kept.
3. The longest word's length. const words = ["sun", "planet", "moon"]; Find the length
of the longest word.
Model answer
const words = ["sun", "planet", "moon"];
const longest = words.reduce((best, w) => Math.max(best, w.length), 0);
console.log(longest); // 6
reduce: many items become one value. best starts at 0 and keeps the larger of itself
and each word's length. words.map((w) => w.length) then Math.max(...) also works.