I still prefer the good old manual loop (much faster, readable and simple):
function Somar(array) {
var total = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] >= 2) {
total += array[i];
}
}
return total;
}
var array = [0, 5, 1, 2];
console.log(Somar(array));
Note that you are not adding indexes but the values of the elements. Index is something else.
If you want to generalize the limit:
function Somar(array, limite) {
var total = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] >= limite) {
total += array[i];
}
}
return total;
}
var array = [0, 5, 1, 2];
console.log(Somar(array, 2));
You can compare and you will see that the speed difference is great. Now demonstrated in another answer.
For those who think that smaller number of lines is better can do, only it is less readable:
function Somar(array, limite) {
for (var i = 0, total = 0; i < array.length; (total += array[i] >= limite ? array[i] : 0), i++);
return total;
}
console.log(Somar([0, 5, 1, 2], 2));
I put in the Github for future reference.
Duplicate question http://answall.com/questions/162676/howto verify themselves bymenos-um%C3%Adndice-do-array-is-equal-or-greater-than-2
– Giovane
Of course not, I asked two questions precisely because they are different.
– durtto