JavaScriptLesson 10 of 16
Array methods: map, filter, reduce
Instead of hand-written loops, arrays have methods that take a function and do the work. The code gets shorter and reads like a sentence: keep what is in stock, take the names.
Key points
- map(fn) builds a new array with every item transformed by the function
- filter(fn) builds a new array with only the items for which fn returns true
- reduce((acc, x) => acc + x, 0) folds the array into one value, starting from 0
- find(fn) returns the first match, some(fn) tells whether there is at least one
- Methods can be chained: list.filter(…).map(…)
Example
const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map((n) => n * 2);const even = numbers.filter((n) => n % 2 === 0);const sum = numbers.reduce((acc, n) => acc + n, 0); console.log(doubled, even, sum);console.log(numbers.find((n) => n > 3), numbers.some((n) => n > 4));console.log(numbers.filter((n) => n > 2).map((n) => n * 10));numbers itself did not change: map and filter return new arrays. On the last line the numbers above 2 were picked first, and then each was multiplied by 10.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.An online store has four products. Keep the ones in stock (filter), take their names (map), add up their prices (reduce) and find the first product in stock that costs more than 20 (find). Output: Mug, Notebook, Hoodie, then Total: 65 and First over 20: Hoodie.
Output
What your program prints appears here.