Lesson 2 · Unit 05
Array methods
map, filter, reduce and friends: say what you want, not how to loop
What you practise
map,filter,reduce,find,someandevery, how the types flow through a chain,sortwith a comparator
Try a question from this lesson
Pick one
map calls the arrow function once for every item and collects the results in a new array. What does this print?
const prices = [5, 10, 20];
const doubled = prices.map((p) => p * 2);
console.log(doubled.join(" "));Correct answer
10 20 40
Why
The arrow function runs three times: with 5, with 10, with 20. Each result goes into the new array at the same position. prices is not touched. You wrote no loop and no counter: map does the walking.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
map: one in, one out
map builds a new array of the same length. You say what happens to one item; it does that to all of them.
The types follow along. Here the arrow function takes a number and returns a string, so the compiler knows the result is a string[] without being told.
const nums = [1, 2, 3];
const labels = nums.map((n) => `#${n}`);
// labels is a string[]
console.log(labels.join(" ")); // #1 #2 #3
console.log(nums.join(" ")); // 1 2 3Concept
reduce: many in, one out
reduce folds an array into a single value. Its arrow function takes the result so far and the next item, and returns the new result. The second argument, 0 here, is where the result starts.
It is the running-total loop from the loops lesson, packed into one call.
const nums = [4, 6, 10];
const sum = nums.reduce(
(total, n) => total + n,
0,
);
console.log(sum); // 20
// total: 0 -> 4 -> 10 -> 20Concept
sort needs a comparator
sort is different in two ways. It changes the array itself, and without help it compares items as text, so 10 comes before 9.
Give it a comparator: an arrow function that takes two items and returns a number. Negative means "a goes first". a - b sorts smallest first; b - a sorts largest first.
const nums = [10, 9, 100];
nums.sort();
console.log(nums.join(" ")); // 10 100 9
nums.sort((a, b) => a - b);
console.log(nums.join(" ")); // 9 10 1009 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.