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(teste));
Note that you are not adding indexes but element values. 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. I already showed in another answer .
For those who think that smaller number of lines is better, 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));