ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 6 · 4లో పాఠం 2కోర్సులో 22/32~12 min
మాడ్యూల్ పాఠాలు (2/4)

తగ్గించండి

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

వ్యాయామం#js.m6.l2.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

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

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

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

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#js.m6.l2.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

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.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

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

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది