Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  27] [ 4]  / answers: 1 / hits: 186685  / 14 Years ago, tue, september 21, 2010, 12:00:00

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 under SpiderMonkey.



Thinking very inside-the-box I have been using:



var count = 0;
for(var i = 0; i < array.length; i++)
{
count = count + array[i];
}


I'm sure there is a better way then straight iteration.


More From » arrays

 Answers
40

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);

[#95549] Saturday, September 18, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;