Skip to main content
eLearner.app
Module 6 · Lesson 2 of 422/32 in the course~12 min
Module lessons (2/4)

reduce

reduce is the most powerful of the functional array methods: it walks through the collection keeping an accumulator that is updated at every step. When the loop is over, it returns the accumulator.

Signature

JS
arr.reduce((acc, elem) => nuovoAcc, valoreIniziale);
  • acc starts at valoreIniziale.
  • For each element a new acc is computed.
  • The final result is the last acc.

Basic examples: sum and product

JS
const numeri = [3, 1, 4, 1, 5];

const somma = numeri.reduce((a, n) => a + n, 0);
// 14

const prodotto = numeri.reduce((a, n) => a * n, 1);
// 60

Without an initial value, reduce starts from the first element (risky on potentially empty arrays → error). Always pass an initial value when you can.

Building an object: counting

JS
const parole = ['mela', 'pera', 'mela', 'kiwi', 'mela'];

const conteggio = parole.reduce((acc, p) => {
  acc[p] = (acc[p] ?? 0) + 1;
  return acc;
}, {});
// { mela: 3, pera: 1, kiwi: 1 }

Finding max / min

JS
const nums = [3, 7, 1, 9, 4];

const max = nums.reduce((a, n) => (n > a ? n : a), -Infinity);
// 9

(In practice for max/min prefer Math.max(...nums); this is a didactic example.)

Try it

Exercise#js.m6.l2.e1
Attempts: 0Loading…

Define `total(items)`: you receive an array of objects { price, quantity } and return the total spending (sum of price*quantity). Use reduce.

Loading editor…
Show hint

reduce((a, it) => a + it.price * it.quantity, 0)

Solution available after 3 attempts

Review exercise

Exercise#js.m6.l2.e2
Attempts: 0Loading…

Define `count(words)`: given an array of strings, return an object that maps each string to the number of occurrences. Use reduce with an object accumulator.

Loading editor…
Show hint

acc[p] = (acc[p] ?? 0) + 1; return acc;

Solution available after 3 attempts