What is the fastest way to sum up an array in JavaScript? A quick search turns over a few different methods, but I would like a native solution if possible. This will run un
Based on this test (for-vs-forEach-vs-reduce) and this (loops)
I can say that:
var total = 0;
for (var i = 0, n = array.length; i < n; ++i)
{
total += array[i];
}
For you case you won't need this, but it adds a lot of flexibility.
Array.prototype.Aggregate = function(fn) {
var current
, length = this.length;
if (length == 0) throw "Reduce of empty array with no initial value";
current = this[0];
for (var i = 1; i < length; ++i)
{
current = fn(current, this[i]);
}
return current;
};
Usage:
var total = array.Aggregate(function(a,b){ return a + b });
Then comes forEach
and reduce
which have almost the same performance and varies from browser to browser, but they have the worst performance anyway.
You should be able to use reduce
.
var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);
Source
And with arrow functions introduced in ES6, it's even simpler:
sum = array.reduce((pv, cv) => pv + cv, 0);
The fastest loop, according to this test is a while loop in reverse
var i = arr.length; while (i--) { }
So, this code might be the fastest you can get
Array.prototype.sum = function () {
var total = 0;
var i = this.length;
while (i--) {
total += this[i];
}
return total;
}
Array.prototype.sum
adds a sum method to the array class... you could easily make it a helper function instead.
one of the simplest, fastest, more reusable and flexible is:
Array.prototype.sum = function () {
for(var total = 0,l=this.length;l--;total+=this[l]); return total;
}
// usage
var array = [1,2,3,4,5,6,7,8,9,10];
array.sum()