JavaScript · Level 2 Arrays

reduce

Fold a whole array into a single result, such as a cart total, by carrying a running value from item to item.

  • reduce((acc, item) => ..., start)
  • The accumulator carries the running result
  • Always pass a starting value

reduce walks the array carrying an accumulator: whatever you return becomes the next acc. Trap: without a starting value, reduce on an empty array throws a TypeError, so always pass one.

const scores = [4, 7, 9];

scores.reduce((acc, n) => acc + n, 0);             // 20
scores.reduce((best, n) => Math.max(best, n), 0);  // 9
[].reduce((acc, n) => acc + n, 0);                 // 0
[].reduce((acc, n) => acc + n);                    // TypeError!

Write cartTotal(items) that returns the sum of price * qty for every item, for example [{ price: 10, qty: 2 }, { price: 5, qty: 1 }] gives 25 (an empty cart gives 0).

solution.js
Test Suites Pending
Output