How to sum the values of an array
Short answer
The reduce() method adds the elements up, starting from zero:
console.log([10, 20, 30].reduce((sum, n) => sum + n, 0));Output:
60The average
Divide the sum by the array length. The check prevents division by zero:
const marks = [4, 5, 3];
const sum = marks.reduce((total, n) => total + n, 0);
console.log(marks.length > 0 ? sum / marks.length : 0);Output:
4Summing a field
Access the property you need inside the function:
const orders = [{ total: 100 }, { total: 250 }];
console.log(orders.reduce((sum, order) => sum + order.total, 0));Output:
350A loop
The same with an ordinary for...of loop:
let sum = 0;
for (const n of [10, 20, 30]) sum += n;
console.log(sum);Output:
60Common mistake
Numbers from forms and files often come as strings. Without converting them, + glues the strings together:
const values = ['10', '20', '30'];
console.log(values.reduce((sum, n) => sum + n, 0));
console.log(values.reduce((sum, n) => sum + Number(n), 0));Output:
0102030
60Functions used in this recipe
- Array.prototype.reduce — Reduces an array to a single value.