Hone

Lessons · JavaScript · folding a list into one value

Fold a list into one value

reduce walks the array carrying an accumulator; each step returns the new accumulator. Start it with an initial value.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Totals, grouping, building objects from arrays: reduce is the general tool, and understanding it makes map and filter click too.

How to think about it

Decide the shape of the answer (a number? an object?) and start with an empty one. Then write the step: given the answer so far and one item, what is the new answer so far?

Worked example

const total = prices.reduce((sum, p) => sum + p, 0);
Accumulator starts at 0; each step adds one price.
const byType = items.reduce((acc, it) => {
Accumulator is an object.
  (acc[it.type] ??= []).push(it); return acc;
Group under its type; return the object for the next step.
}, {});
Start empty.

Your turn

Find the longest word.

const longest = words.reduce((best, w) => w.length > best.length ? w : , "");

The trap

Omitting the initial value: reduce then uses the first item as the accumulator and crashes on an empty array.

Practise folding a list into one value on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.