# How to optimize the sum of the elements of an array

8

I need to get the value of the sum of the items of a `array` in JavaScript.

The amount of these items can easily reach 2,000 items. Items are of type `int` , no testing required.

``````ar = [1,3,5,...,2000];
``````

I already have a `array` containing the elements, I do not need to get the value in the inputs . I want to add the elements of this `array` , in a clear and objective way.

Is this correct? Will I lose by tying?

``````for (f=0;f<60;f++)
{
valorSoma = ar[f]+valorSoma;
}
``````

asked by anonymous 27.10.2016 / 18:07

10

If you want the most performative way:

``````var ar = [1,3,5,8,2000];
for (var i = 0, total = 0; i < ar.length; total += ar[i++]);
console.log(total);``````

My result by comparing `for` , `for` with `length` external (contrary to popular belief is slower than leaving internal), `reduce()` and `forEach()` :

So your way is correct, even though you're only getting 60 items and not writing as well as you can. I made the shortest possible (since the comparison seems to be using a ready function) without losing performance.

27.10.2016 / 18:19
8

From ES6, you can use `Array.reduce` with arrow functions :

``````var numeros = [1, 3, 4, 2000];
var soma = numeros.reduce((a, b) => a + b);

console.log(soma);``````

Another alternative with `while` :

``````var numeros = [1, 3, 4, 2000];
var tamanho = numeros.length;
var total = 0;

while(tamanho--) {
total += numeros[tamanho];
}

console.log(total);``````

27.10.2016 / 18:55
5

Use reduce

``````var meuArray = [1, 2, 3, 200];

var countArray = meuArray.reduce(function(total, item) {