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
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
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.
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;
}));
The best way is using a for loop. Is not the shortest, but is the best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With