Course outline · 0% complete

0/29 lessons0%

Course overview →

reduce: fold to a single value

lesson 7-3 · ~10 min · 24/29

One value out

map and filter give arrays back. reduce combines all the items into one result: a total, a maximum, a combined string.

const nums = [1, 2, 3, 4];
const sum = nums.reduce((total, n) => total + n, 0);   // 10

Two arguments to reduce:

  1. An arrow taking (accumulator, item). The accumulator is the running result so far. Whatever the arrow returns becomes the accumulator for the next item.
  2. The starting value for the accumulator (0 here).

Trace the sum: start 0, then 0+1=1, 1+2=3, 3+3=6, 6+4=10. It is exactly the sum loop from lesson 4-3, with the machinery folded in. If reduce feels dense, write the loop first and translate. Both are correct, and reduce is the one you will read constantly in other people's code.

Code exercise · javascript

Run it. The sum starts at 0. The max uses Math.max from lesson 1-2 as the combining step and starts from the first item.

Code exercise · javascript

Your turn. Total the cart with reduce and print the result.

Code exercise · javascript

Second practice. Use reduce to find the LONGEST word. The accumulator holds the best word so far; each step the arrow returns whichever of (best, w) is longer. Start from words[0] and print the winner.

Problem

Trace by hand: [2, 3, 4].reduce((acc, n) => acc * n, 1). What number results?