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
arr.reduce((acc, elem) => nuovoAcc, valoreIniziale);accstarts atvaloreIniziale.- For each element a new
accis computed. - The final result is the last
acc.
Basic examples: sum and product
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);
// 60Without 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
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
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
Define `total(items)`: you receive an array of objects { price, quantity } and return the total spending (sum of price*quantity). Use reduce.
Show hint
reduce((a, it) => a + it.price * it.quantity, 0)
Solution available after 3 attempts
Review exercise
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.
Show hint
acc[p] = (acc[p] ?? 0) + 1; return acc;
Solution available after 3 attempts