メインコンテンツにスキップ
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 回の試行後に解決策が利用可能になります