How to find the sum of an array of numbers

How to find the sum of an array of numbers

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)
I thought $.each might be useful, but I’m not sure how to implement it.

Solutions/Answers:

Solution 1:

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)

Without default value

You get a TypeError

console.log(
  [].reduce((a, b) => a + b)
)

Prior to ES6’s arrow functions

console.log(
  [1,2,3].reduce(function(acc, val) { return acc + val; }, 0)
)

console.log(
  [].reduce(function(acc, val) { return acc + val; }, 0)
)

Non-number inputs

If non-numbers are possible inputs, you may want to handle that?

console.log(
  ["hi", 1, 2, "frog"].reduce((a, b) => a + b)
)

let numOr0 = n => isNaN(n) ? 0 : n

console.log(
  ["hi", 1, 2, "frog"].reduce((a, b) => 
    numOr0(a) + numOr0(b))
)

Non-recommended dangerous eval use

We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into “1+2+3”, which evaluates to 6.

console.log(
  eval([1,2,3].join('+'))
)

//This way is dangerous if the array is built
// from user input as it may be exploited eg: 

eval([1,"2;alert('Malicious code!')"].join('+'))

Of course displaying an alert isn’t the worst thing that could happen. The only reason I have included this is as an answer Ortund’s question as I do not think it was clarified.

Solution 2:

In Lisp, this’d be exactly the job for reduce. You’d see this kind of code:

(reduce #'+ '(1 2 3)) ; 6

Fortunately, in JavaScript, we also have reduce! Unfortunately, + is an operator, not a function. But we can make it pretty! Here, look:

const sum = [1, 2, 3].reduce(add,0); // with initial value to avoid when the array is empty

function add(accumulator, a) {
    return accumulator + a;
}

console.log(sum); // 6

Isn’t that pretty? 🙂

Even better! If you’re using ECMAScript 2015 (aka ECMAScript 6), it can be this pretty:

const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0); 
console.log(sum); // 6

Solution 3:

Why not reduce? It’s usually a bit counter intuitive, but using it to find a sum is pretty straightforward:

var a = [1,2,3];
var sum = a.reduce(function(a, b) { return a + b; }, 0);

Solution 4:

var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }

Solution 5:

var total = 0;
$.each(arr,function() {
    total += this;
});

Solution 6:

This is possible by looping over all items, and adding them on each iteration to a sum-variable.

var array = [1, 2, 3];

for (var i = 0, sum = 0; i < array.length; sum += array[i++]);

JavaScript doesn’t know block scoping, so sum will be accesible:

console.log(sum); // => 6

The same as above, however annotated and prepared as a simple function:

function sumArray(array) {
  for (
    var
      index = 0,              // The iterator
      length = array.length,  // Cache the array length
      sum = 0;                // The total amount
      index < length;         // The "for"-loop condition
      sum += array[index++]   // Add number on each iteration
  );
  return sum;
}