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

Asked

Viewed 7,032 times

7

I have the following array:

array[0,2,0,0];

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

In this example you must return me 2; array[0,2,0,0];

In this example should return me 7; array[0,5,1,2];

  • Duplicate question http://answall.com/questions/162676/howto verify themselves bymenos-um%C3%Adndice-do-array-is-equal-or-greater-than-2

  • Of course not, I asked two questions precisely because they are different.

5 answers

8


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.

  • It may perform better due to overhead in function call, but I don’t find it more readable. Reduce, filter, map makes code more optimized and, for those who understand, simpler.

  • 1

    It does not leave more optimized, as just conformed, readability is a little subjective, I find my good more readable, any minimally educated programmer understands it well, the other forms is not whatever you understand. You have to look elsewhere or understand a syntax at least weird. There is nothing simple about having to use two functions where a very simple one fits, even worse if you have to write two and call the other two and to abstract it would have to have a farm. Nothing simple. But as I said, who likes... likes.

  • It may be a matter of opinion, but it does make it simpler. A block of code with nested and conditional loops in my opinion is no longer readable. ECMA2015 has implemented these functions and I follow the worldwide javascript community, is being adopted by the majority. Line reduction means optimization. Any test that is done for jobs or on programming platforms (Hackerrank, facebook Event developers, etc) is heavy the use of ECMA2015 and often the first question of the evaluator is: "Why was used nested loops if there is reduce in ECMA2015?"

  • 1

    but I don’t find it readable anymore is very subjective @Lucascosta

  • 2

    PS: I hope they don’t confuse, so let’s be clear: I think it’s important to have both forms in the answers, and I think they both have their spaces. What you don’t get is to face personal taste by hinting at the wrong thing, like reducing is better. It’s just a sugar, a convenience, which in certain situations can be practical. Nothing more.

  • @Bigown, I don’t understand C# about the reference. At first I agreed with you that this way has better performance, I thought you would understand that with optimized wanted to emphasize optimizes on lines of code. Thank you for sharing your knowledge.

  • 3

    @Lucascosta Decreasing the number of lines does not bring an advantage by itself. Mine has two more lines. I made a version with only 5 lines, much less than yours, which has nothing wrong. It was no more readable than my previous ones. Whether it’s more readable than yours is debatable. Piling up everything is not readable, but separate in various things, being requiring extra steps to consume can not call the most readable that gives also. Particularly I find it less readable, but I accept those who say it is more readable. Subjective things are like that. That’s why I cling more to objectives. I earn more

  • These comments about code optimization throw me the matter of complexity of algorithms, remembering that the complexity of a recursive algorithm (case of reduce that calls the same function while there is an element inside the array, ie a loop running a function n times) is in the best case O(n). Already in an algorithm using only one loop, the best case, and the worst case is the same O(n). See as reference, from slide 20: link

  • Of course, in the example of the question, performance would not affect much, since the function within reduce is called only once, but I emphasize that in the optimization of an algorithm should not always be taken into account the number of lines or readability, but rather its performance

  • @Marcelobonifazio did not analyze this question, it may be too, but there is the disadvantage of overhead function being called in all iterations and elimination of optimizations occurring in the loop also. Even in the best case the reduce() will be well worst.

  • @Augustovasques ah yes, thank you.

Show 6 more comments

6

You can use the .reduce (ES5) or a cycle 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: https://jsfiddle.net/btg0ag08/1/

5

First you can get an array of values that are greater than or equal to 2 using Array#filter and then use the Array#reduce to effect 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

5

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

You could try doing something like using a cleaner while if it’s to "make 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");

2

You can filter and use the reduce function to sum 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));

reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Browser other questions tagged

You are not signed in. Login or sign up in order to post.