Lesson 2 · Unit 05
Array methods
map, filter, reduce and a sort that works
What you practise
map,filter,reduce,find,someandevery, chaining them,sortwith a comparator and the default sort that orders 10 before 9
Try a question from this lesson
Pick one
map calls the arrow function once for every item and collects what it returns in a new array. What prints?
const prices = [5, 8, 12];
const doubled = prices.map((p) => p * 2);
console.log(doubled.join(" "));Correct answer
10 16 24
Why
The function runs three times: with 5, with 8 and with 12. Each result goes into the new array at the same position. You wrote no loop and no push: map did both.
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 takes a function and returns a new array: the same length, with every item replaced by what the function returned for it.
The original array is not changed. It is the loop you have written many times, with the loop itself hidden.
const prices = [5, 8, 12];
// by hand
const out = [];
for (const p of prices) {
out.push(p * 2);
}
// the same, with map
const doubled = prices.map((p) => p * 2);Concept
reduce: many in, one out
reduce boils an array down to a single value. It carries a running result from item to item.
You give it a function and a starting value. The function gets the running result and the next item, and returns the new running result.
const nums = [4, 6, 10];
const total = nums.reduce(
(sum, n) => sum + n,
0, // sum starts here
);
console.log(total); // 20
// sum goes 0 -> 4 -> 10 -> 20Concept
sort with a comparator
Give sort a function that takes two items. Return a negative number when the first belongs first, a positive number when the second does.
For numbers, a - b sorts smallest first and b - a largest first.
Unlike map and filter, sort changes the array itself. Copy it first with spread if you need the original.
const nums = [9, 10, 1];
nums.sort((a, b) => a - b);
console.log(nums.join(" ")); // 1 9 10
const top = [...nums]; // a copy
top.sort((a, b) => b - a);
console.log(top.join(" ")); // 10 9 1
console.log(nums.join(" ")); // 1 9 109 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.