Arrays: map, filter, and reduce
array.map(fn) builds a new array by running fn on every item and keeping
whatever it returns - same length in and out, values transformed.
array.filter(fn) builds a new array by keeping only the items where fn
returns true - same values, fewer of them. Neither touches the original array.
Both take an arrow function: n => n * 2 doubles, n => n % 2 === 0 checks
for even. You'll reach for this pair constantly - it replaces most of the loops
you'd otherwise write to transform or narrow down a list.
Sometimes you don't want a new array at all - you want one value out of it, like
a total. array.reduce((acc, n) => acc + n, 0) walks the array once, carrying
an accumulator (acc, starting at 0) forward and adding each item to it -
exactly how you'd total up a list without writing your own loop.
Your task: given the array nums, create doubled (every number doubled),
evens (only the even numbers), and total (the sum of every number in nums).
You'll practice:
Transforming an array with .map()
Narrowing an array with .filter()
Collapsing an array to one value with .reduce()
Show a hint
Show solution
Previous Next