How to sum up an array of integers with javascript

fa? js does not have sum method for array!?

Javascript does not have Array.prototype.sum() actually but js can calculate with;

  • for loop
  • for in loop
  • forEach loop
  • map loop
  • reduce loop
1
2
// set up
const arr = [1, 2, 3, 4, 5];

♻️ for loop

1
2
3
4
5
6
7
let totalFor = 0;

for (let i = 0; i < arr.length; i++) {
totalFor += arr[i];
}

console.log({ totalFor }); // { totalFor: 15 }

♻️ for in loop

1
2
3
4
5
6
let totalForIn = 0;
for (let i in arr) {
totalForIn += arr[i];
}

console.log({ totalForIn }); // { totalForIn: 15 }

♻️ forEach loop

1
2
3
4
let totalForEach = 0;
arr.forEach((elm) => (totalForEach += elm));

console.log({ totalForEach }); // { totalForEach: 15 }

♻️ map loop

1
2
3
4
let totalMap = 0;
arr.map((value) => (totalMap += value));

console.log({ totalMap }); // { totalMap: 15 }

♻️ reduce loop

1
2
3
const totalReduce = arr.reduce((acc, cur) => acc + cur, 0);

console.log({ totalReduce }); // { totalReduce: 15 }

Summary

  • In terms of the performance, for and reduce seems very good performance 🏆
    https://jsben.ch/MlsMo
  • Readability: reduce looks the simplest 🏆

==> 👑 reduce