I was wondering if anyone knows of a nice way of adding an array of values in javascript?
I came up with:
var myArray = [1,2,3,4,5];
var total = eval(myArray.join("+"));
Which is nice and short, but I'm guessing going from num to string and then evaling to get back to a number is a slow way of getting the total.
I was wondering if anyone knows of a nice way of adding an array of values in javascript?
I came up with:
var myArray = [1,2,3,4,5];
var total = eval(myArray.join("+"));
Which is nice and short, but I'm guessing going from num to string and then evaling to get back to a number is a slow way of getting the total.
Share Improve this question edited Feb 10, 2011 at 12:35 Andy E 345k86 gold badges481 silver badges451 bronze badges asked Feb 10, 2011 at 12:25 DavidDavid 631 silver badge4 bronze badges 4- Yep I'd say that's definitely inefficient! – El Ronnoco Commented Feb 10, 2011 at 12:26
-
1
Why would you avoid loops? Much less use
eval
for this? – user395760 Commented Feb 10, 2011 at 12:27 -
1
eval
is evil. Didn't you get the memo? – Andy E Commented Feb 10, 2011 at 12:35 - Possible duplicate of How to find the sum of an array of numbers – Mohammad Usman Commented Sep 30, 2018 at 11:20
2 Answers
Reset to default 5The most appropriate method of doing this is to use the [Array.prototype.reduce
](
https://developer.mozilla/en/JavaScript/Reference/Global_Objects/Array/reduce) function, an addition to the language in ECMAScript 5th Edition:
var myArray = [1,2,3,4,5],
total = myArray.reduce(function (curr, prev) { return curr + prev; });
alert(total);
Of course, this isn't supported in older browsers so you might want to include the patibility implementation in your code.
UPDATE - To bine Andy's method and the Prototyping method...
Array.prototype.sum = function(){
return this.reduce(function(a,b) {return a+b} );
}
Now all array will have the sum
method. eg var total = myArray.sum();
.
Original answer...
I'd be tempted with just
var myArray = [1,2,3,4,5];
var sum = 0;
for (var i=0, iMax=myArray.length; i < iMax; i++){
sum += myArray[i];
};
alert(sum);
break it out into a function if you're using it a lot. Or even neater, prototype it...
Array.prototype.sum = function(){
for(var i=0, sum=0, max=this.length; i < max; sum += this[i++]);
return sum;
}
var myArray = [1,2,3,4,5];
alert(myArray.sum());
Courtesy of DZone Snippets