Sum of Nodejs + Mongoose values

Asked

Viewed 1,283 times

1

I need to sum the values stored in a variable in the bank.

I have a form and want to know the total value generated in a variable.

So I did it this way:

               _.each(cliente.data, function (data) {
                  for(i=0; i>=cliente.data.length; i++){
                    var valor= data.valor;

                  }
                });

While i >= visit.oppEY.length(my vector) should add the values accumulated in the value variable.

But I have tried in many ways and the only thing that happens is the increase of values.

1 answer

5


I believe you want something like this:

var valor = 0;
_.each(cliente.data, function (data) {
    valor+= Number(data.valor);
});

You’re already iterating on cliente.data, would not need another loop(the for) within the each. And also, you’re re-declaring the variable valor within the loop at each iteration, which will prevent adding the value in it. By declaring outside the loop the value is maintained.

In fact, the condition of his for should be i <= cliente.data.length and not i >= cliente.data.length, for i started in 0 will always be smaller than your array if there is data in it.

  • I get it. But the problem of this model you made is the same as mine. It doesn’t add up, it just adds up the values. It looked like this: I had a value of 90,000 and another of 300.00 = 090.000300.00. This was the result, it did not add up.

  • @Nodejs ah yes, I was going to comment on that. Try valor+= Number(data.valor);.

  • Perfect. It worked. Thank you so much !

  • @Nodejs ok, you’re welcome.

Browser other questions tagged

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