Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to calculate the sum of array elements

Tags:

javascript

I'm trying to find the fastest way to calculate the sum of elements contained in an array.
I managed to do it using eval(), but i consider eval as evil.

var arr = [10,20,30,40,50];
console.log( eval( arr.join('+') ) ); //logs 150

Is there a better way to do it other than using a for loop ?

I was thinking more about something like that, but it doesn't work:

var arr = [10,20,30,40,50];  

console.log( new Number( arr.join('+') ) ); //logs a Number Object  

console.log( new Number( arr.join('+') ).toString() ); //logs NaN
like image 203
Pierre Avatar asked Jan 07 '12 21:01

Pierre


People also ask

How do you sum two arrays?

The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum.


2 Answers

If supported you can use the reduce method of Array

var arr = [10, 20, 30, 40, 50];

console.log(arr.reduce(function(prev, cur) {
    return prev + cur;
}));
like image 192
Andreas Avatar answered Oct 21 '22 02:10

Andreas


The best way is using a for loop. Is not the shortest, but is the best.

like image 24
Ivan Castellanos Avatar answered Oct 21 '22 02:10

Ivan Castellanos