मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 6 · पाठ 2 का 4पाठ्यक्रम में 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 प्रयासों के बाद समाधान उपलब्ध है