Add the values in a list
Add every item once. Repeated values still count each time they occur.
Array.reduce
Simple example
Add one, two and three.
Start1 · 2 · 3
Result6
const values = [1, 2, 3];
console.log(values.reduce((total, value) => total + value, 0));
6
Advertisements
Everyday examples
Add the three amounts on a receipt.
Start5 · 5 · 8
Result18
const values = [5, 5, 8];
console.log(values.reduce((total, value) => total + value, 0));
18
How many passengers boarded at the three stops?
Start2 · 7 · 1
Result10
const values = [2, 7, 1];
console.log(values.reduce((total, value) => total + value, 0));
10
How many exercise books arrived in three boxes?
Start10 · 8 · 9
Result27
const values = [10, 8, 9];
console.log(values.reduce((total, value) => total + value, 0));
27