Array methods: map, filter, reduce
Transform and summarize lists with the array methods you will use every day.
20 min
Loops work, but most list jobs have a name, and JavaScript gives each one a method. These take a function and run it for every item.
const nums = [1, 2, 3, 4];
nums.map(n => n * 2); // [2, 4, 6, 8] transform each
nums.filter(n => n % 2 === 0); // [2, 4] keep some
nums.find(n => n > 2); // 3 the first match (or undefined)
nums.some(n => n > 3); // true is any true?
nums.every(n => n > 0); // true are all true?
nums.reduce((sum, n) => sum + n, 0); // 10 fold into one valuemap returns an array the same length. filter returns a shorter or equal one. reduce takes a function (running, item) => newRunning and a starting value, and returns one value: always give the start value.
Each method returns a new array, so you can chain them left to right:
people
.filter(p => p.age >= 18)
.map(p => p.name)
.join(", ");Read it as a recipe: keep adults, take their names, join with commas. None of these change the original array.
sort changes the array in place and, by default, compares items as text: [10, 9, 1].sort() is [1, 10, 9]. For numbers pass a compare function: arr.sort((a, b) => a - b) is ascending, b - a is descending. To keep the original, sort a copy: [...arr].sort(...).
| You want | Use |
|---|---|
| one value per item | map |
| some of the items | filter |
| one item | find |
| yes or no | some, every, includes |
| one answer from the list | reduce (or a loop) |
| each item for a side effect | forEach or for...of |
A chain reads like a recipe: each step feeds the next.
Use reduce to find the average of [4, 8, 15, 16, 23, 42].
- 1
const nums = [4, 8, 15, 16, 23, 42];
The data.
Write adultNames(people). people is an array of { name, age } objects. Return an array of the names of people aged 18 or over, in the same order.
Your code must satisfy
- adultNames([{name: "Ada", age: 36}, {name: "Bo", age: 12}, {name: "Cy", age: 18}])→["Ada","Cy"]mixed
- adultNames([{name: "Bo", age: 12}])→[]none
- adultNames([])→[]empty
function adultNames(people) {
}Write average(nums) using reduce. It returns the mean, or 0 for an empty array.
Your code must satisfy
- average([2, 4, 6])→4simple
- average([1, 2])→1.5decimal
- average([])→0empty
- average([7])→7one
function average(nums) {
}sortNumbers(arr) should return a new array in ascending numeric order, but it gives the wrong order for numbers with different digits. Fix it.
What it does now
sortNumbers([10, 9, 1, 100]) returns [1, 10, 100, 9].
Your code must satisfy
- sortNumbers([10, 9, 1, 100])→[1,9,10,100]mixed digits
- sortNumbers([1, 2, 3])→[1,2,3]already sorted
- sortNumbers([3, -1, 2])→[-1,2,3]negatives
- sortNumbers([])→[]empty
function sortNumbers(arr) {
return [...arr].sort();
}“`nums.map(...)` changes `nums`.”
It sounds like it applies a change to the array.
What is actually true
map, filter and reduce return new values and leave the original array alone. If you drop the result, nothing is saved: nums.map(n => n * 2); on its own line does nothing useful.
How to catch yourself
Store the result: `const doubled = nums.map(...)`.
maptransforms each item;filterkeeps some;findreturns the first match;reducefolds a list into one value.- These methods return new values and chain left to right.
sortchanges the array and sorts as text unless you give(a, b) => a - b.- Always give
reducea starting value.
Method checks.
What is [1, 2, 3].map(n => n * n)?
- A[1, 2, 3]
- B[1, 4, 9]
- C14
- D[2, 4, 6]
What is [5, 8, 12].filter(n => n > 6)?
- A[8, 12]
- B[5]
- C[8]
- D2
What is [1, 2, 3, 4].reduce((a, n) => a + n, 0)?
What does [3, 7, 9].find(n => n > 5) return?
- A[7, 9]
- B7
- Ctrue
- D1
What is [10, 9, 1].sort()?
- A[1, 9, 10]
- B[1, 10, 9]
- C[10, 9, 1]
- D[9, 10, 1]
Choose a list in your life (expenses, tasks, scores). Which of map, filter, find and reduce would answer a real question about it, and what question?
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of JavaScript for Beginners is planned around your week. Free.