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
  • 338,112
  • 86
  • 474
  • 445
David
  • 63
  • 1
  • 4

2 Answers2

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.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 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? – El Ronnoco Feb 10 '11 at 12:47
  • Thanks, this is what I was looking for, I googled but didn't think to look on MDN. – David Feb 10 '11 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?). –  Feb 10 '11 at 12:50
  • @El: I would expect the native `reduce` to run faster, but not the compatibility implementation. – Andy E Feb 10 '11 at 12:52
  • @delnan when you say 'it would run slightly faster' do you mean the `reduce` or the custom protoype? – El Ronnoco Feb 10 '11 at 12:56
  • @El Ronnoco: Your hand-rolled loop. –  Feb 10 '11 at 12:57
2

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

El Ronnoco
  • 11,753
  • 5
  • 38
  • 65
  • *Please* format properly. If the code seems to convulted, dropping formatting (in particular whitespace) is *not* an acceptable response. –  Feb 10 '11 at 12:34
  • @delnan I'm sorry, what exactly are you referring to? – El Ronnoco Feb 10 '11 at 12:36
  • @delnan - Do you mean the `for` loop formatting - if so, I have fixed it :) – El Ronnoco Feb 10 '11 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. –  Feb 10 '11 at 12:38
  • @delnan I think the spaces round operators debate it ongoing :) Neither style offends my eye particularly. – El Ronnoco Feb 10 '11 at 12:41
  • I was tempted too, but I love all the tricks in javascript to perform operations with only a line or two. – David Feb 10 '11 at 12:52
  • Also it might be more efficient to implment with a while loop and pop() since then you are not updating i each iteration of the loop. Thanks for your suggestions :) – David Feb 10 '11 at 12:53
  • @David well the beauty of this trick is that once you've defined the protoype method you can call `.sum()` on any numeric array and there you go, 6 characters! – El Ronnoco Feb 10 '11 at 12:57