Combine array elements into one value.

Reducing to a Total

reduce_total.js
const bonus = 0;
const costs = [3, 4, 5];
const total = costs.reduce((sum, cost) => sum + cost, bonus);

console.log("bonus=" + bonus);
console.log("total=" + total);

Follow the Accumulator

  1. Start the accumulator with bonus.
  2. Add the first cost to get the next accumulator.
  3. Keep passing the new accumulator to the next callback.
  4. The final accumulator becomes total. | Step | Cost | Accumulator after step | | --- | --- | --- | | start | none | bonus | | 1 | 3 | bonus + 3 | | 2 | 4 | previous total + 4 | | 3 | 5 | previous total + 5 |
reduce-total `reduce` carries an accumulator from one callback call to the next. The initial value is the starting accumulator.

Exercise: reduce_total.js

Use reduce to add item costs starting from a bonus value and print the final total