Higher-Order Array Methods
Reducing to a Total
Combine array elements into one value.
reduce-total
`reduce` carries an accumulator from one callback call to the next. The initial value is the starting accumulator.
Reducing to a Total
reduce_total.js
Replay: real traced execution (multi-file project)
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);
const bonus = 5;
const costs = [3, 4, 5];
const total = costs.reduce((sum, cost) => sum + cost, bonus);
console.log("bonus=" + bonus);
console.log("total=" + total);
const bonus = 10;
const costs = [3, 4, 5];
const total = costs.reduce((sum, cost) => sum + cost, bonus);
console.log("bonus=" + bonus);
console.log("total=" + total);
bonus ← 0, costs ← 3,4,5, total ← 12
1const bonus→ 0 = 0; //@bonus=5, 102const costs→ 3,4,5 = [3, 4, 5];3const total→ 12 = costs3,4,5.reduce((sum, cost) => sum + cost, bonus0);45console.log("bonus=" + bonus0);6console.log("total=" + total12);outputbonus=0 total=12
bonus ← 5, costs ← 3,4,5, total ← 17
1const bonus→ 5 = 5;2const costs→ 3,4,5 = [3, 4, 5];3const total→ 17 = costs3,4,5.reduce((sum, cost) => sum + cost, bonus5);45console.log("bonus=" + bonus5);6console.log("total=" + total17);outputbonus=5 total=17
bonus ← 10, costs ← 3,4,5, total ← 22
1const bonus→ 10 = 10;2const costs→ 3,4,5 = [3, 4, 5];3const total→ 22 = costs3,4,5.reduce((sum, cost) => sum + cost, bonus10);45console.log("bonus=" + bonus10);6console.log("total=" + total22);outputbonus=10 total=22
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|
Exercise: reduce_total.js
Use reduce to add item costs starting from a bonus value and print the final total