Bitpath

Lesson 2 · Unit 05

Array methods

map, filter, reduce and friends: say what you want, not how to loop

13 exercisesabout 3 min

What you practise

  • map, filter, reduce, find, some and every, how the types flow through a chain, sort with 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?

TypeScript
const prices = [5, 10, 20];
const doubled = prices.map((p) => p * 2);
console.log(doubled.join(" "));

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.

TypeScript
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 3

Concept

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.

TypeScript
const nums = [4, 6, 10];
const sum = nums.reduce(
  (total, n) => total + n,
  0,
);
console.log(sum); // 20

// total: 0 -> 4 -> 10 -> 20

Concept

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.

TypeScript
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 100

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy