How to return the sum of numbers of an array with indices of value greater than or equal to 2

5

I have the following array:

array[0,2,0,0];

I need to create a function that adds only the indexes with values greater than or equal to two, how should I proceed?

  

In this example I should return 2;       array [0,2,0,0];

     

In this example, you should return 7;         array [0.5,1,2];

    
asked by anonymous 01.11.2016 / 18:37

5 answers

4

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));
    
01.11.2016 / 18:49
4

You can first get an array of values that are greater than or equal to 2 using Array # filter and then use the Array # reduce to infer the sum:

function somarMaiorIgualQueDois(element, index, array) {
  return element >= 2;
}

function add(a, b) {
    return a + b;
}

var res = [0,5,1,2].filter(somarMaiorIgualQueDois);
var soma = res.reduce(add, 0);

console.log(soma); // 7

function somarMaiorIgualQueDois(element, index, array) {
  return element >= 2;
}

function add(a, b) {
  return a + b;
}

var res = [0, 2, 0, 0].filter(somarMaiorIgualQueDois);
var soma = res.reduce(add, 0);

console.log(soma); // 7
    
01.11.2016 / 18:43
4

You can use .reduce (ES5) or for (old fashioned).

Examples of both:

var arr = [0, 2, 0, 0, 3, 5]; // a soma deve ser 10
var valor = 2;

function sumFor(arr, nr) {
    var soma = 0;
    for (var x = 0, l = arr.length; x < l; x++) {
        if (arr[x] >= nr) soma += arr[x];
    }
    return soma;
}

function sumReduce(arr, nr) {
    return arr.reduce(
        (sum, val) => sum + (val >= nr ? val : 0)
    );
}

console.log(sumFor(arr, valor));
console.log(sumReduce(arr, valor));

jsFiddle: link

    
01.11.2016 / 18:51
3

This is just an alternative suggestion and contains an example performance test that you can use in all scripts (although performance on this kind of thing will be totally imperceptible)

You could try to do something like use a cleaner while, if it is to "make more readable" code writing:

/*
arr = seu array
min = valor minimo que o indice deve ter
*/

function SomaArray(arr, min)
{
    var sum = 0,
        i = arr.length; 

    while (i--) {
        current = arr[i];
        if (current >= min) sum += current;
    }

    return sum;
}

var meuArray = [0, 0, 5, 2, 1, 0];
var initiate = new Date().getTime();

console.log(SomaArray(meuArray, 2));

console.log("Terminou em:", new Date().getTime() - initiate, "ms");
    
01.11.2016 / 20:16
1

You can make a filter and use the reduce function to add the resulting components:

var teste = [0,2,0,0];

function adicionar(a, b) {
    return a + b;
}

function somar(array) {
  return array.filter(function(item) {
    return item >= 2;
  }).reduce(adicionar, 0);
}

console.log(somar(teste));
    
01.11.2016 / 18:41