4

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.

Andy E
346k86 gold badges482 silver badges452 bronze badges
asked Feb 10, 2011 at 12:25
4
  • Yep I'd say that's definitely inefficient! Commented Feb 10, 2011 at 12:26
  • 1
    Why would you avoid loops? Much less use eval for this? Commented Feb 10, 2011 at 12:27
  • 1
    eval is evil. Didn't you get the memo? Commented Feb 10, 2011 at 12:35
  • Possible duplicate of How to find the sum of an array of numbers Commented Sep 30, 2018 at 11:20

2 Answers 2

5

The most appropriate method of doing this is to use the [Array.prototype.reduce]( https://developer.mozilla.org/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 compatibility implementation in your code.

answered Feb 10, 2011 at 12:41
6
  • Would this execute faster than protoype.sum function in my answer? This isn't a criticism btw I was not aware of the reduce function and it looks very useful but I would think that for something as simple as summing perhaps the sum would run faster? Commented Feb 10, 2011 at 12:47
  • Thanks, this is what I was looking for, I googled but didn't think to look on MDN. Commented Feb 10, 2011 at 12:50
  • @El Ronnoco: It would propably run slightly faster, but not even noticeable unless the array is really huge. What really bugs me about this solution is the verbose lambda needed for summing... operator sections are awesome (sum = reduce (+) anyone?). Commented Feb 10, 2011 at 12:50
  • @El: I would expect the native reduce to run faster, but not the compatibility implementation. Commented Feb 10, 2011 at 12:52
  • @delnan when you say 'it would run slightly faster' do you mean the reduce or the custom protoype? Commented Feb 10, 2011 at 12:56
1

UPDATE - To combine 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

answered Feb 10, 2011 at 12:32
8
  • Please format properly. If the code seems to convulted, dropping formatting (in particular whitespace) is not an acceptable response. Commented Feb 10, 2011 at 12:34
  • @delnan I'm sorry, what exactly are you referring to? Commented Feb 10, 2011 at 12:36
  • @delnan - Do you mean the for loop formatting - if so, I have fixed it :) Commented Feb 10, 2011 at 12:38
  • @El Ronnoco: (Edit: Yes, although it could still be improved IMHO ;)) The loops. In about every sensible coding style, it would include two or three line breaks and spaces around operators. Commented Feb 10, 2011 at 12:38
  • @delnan I think the spaces round operators debate it ongoing :) Neither style offends my eye particularly. Commented Feb 10, 2011 at 12:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.