Higher-Order Array Methods
Reducing to a Total
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
- Start the accumulator with
bonus. - Add the first cost to get the next accumulator.
- Keep passing the new accumulator to the next callback.
- 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