Sub topic 2
How Array Method Callbacks Work
This chapter assumes you know arrow functions and how to create and index arrays.
The callback signature
A callback is a function you pass to another function, which then calls it for you. Methods such as map, filter, and reduce call your callback once for each element. For map and filter the arguments are (element, index, array). Most callbacks only use element, but the other two are passed every time.
const prices = [10, 20, 30];
const labels = prices.map((p, i, arr) => `${i + 1}/${arr.length}: ${p}`);
console.log(labels); // ['1/3: 10', '2/3: 20', '3/3: 30']Transforming with map
map returns a new array of the same length. Each slot holds whatever your callback returned for that element. The original array is not changed. If your callback forgets to return, which often happens with a braced arrow body, every slot becomes undefined.
const doubled = [1, 2, 3].map(n => n * 2);
console.log(doubled); // [2, 4, 6]Selecting with filter
filter returns a new array containing only the elements for which the callback returned a truthy value. The result can be shorter than the original, or empty.
const cheap = [10, 20, 30].filter(p => p < 25);
console.log(cheap); // [10, 20]Aggregating with reduce
reduce combines all elements into one value. Its callback receives (accumulator, element, index, array). Whatever the callback returns becomes the accumulator for the next call. The second argument to reduce sets the starting accumulator.
const total = [10, 20, 30].reduce((sum, p) => sum + p, 0);
console.log(total); // 60Always pass an initial value. If you leave it out, reduce uses the first element as the starting accumulator, and it throws a TypeError on an empty array.
Exercise
What does [1, 2, 3, 4].filter(n => n % 2).map(n => n * 10) return, and why?
Show answer
[10, 30]. n % 2 is 1 (truthy) for odd numbers and 0 (falsy) for even ones, so filter keeps 1 and 3. Then map multiplies each by 10.
Exercise
Use reduce to count how many strings in ['a', 'bb', 'ccc'] are longer than 1 character.
Show answer
['a', 'bb', 'ccc'].reduce((count, s) => s.length > 1 ? count + 1 : count, 0) returns 2.