How to sum a number array in Javascript?

In this snippet we will use the Reduce method to sum a number array in Javascript.

In the first, we create a function called getSumArray with some codes bellow:
function getSumArray(array) {
   if (array.length <= 0) {
     return 0; // Return 0 with array without value
   return array.reduce((total, num) => total + num);

In the codes above, we use the reduce() method executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator (total is this case).
Note: this method does not change the original array.


const arrayNumbers = [15, 30, 40, 25, 50];
const sum = getSumArray(arrayNumbers); // 160


© 2019 4codev

Created with love by Sil.