How to add numerical values from an array?

Asked

Viewed 2,829 times

0

I would like to know how I can get the sum of numerical values within a matrix. My case is the following, I am building a sales screen, currently I have an array with the products that the user selects to sell, I am displaying them on the screen normally. However I need to capture each value (price) of each product, and in the end I need to add up all prices to reach the total value of the sale, but I’m not sure how to do.

My current structure is as follows: :

//Capturo o objeto produto que foi selecionado, 1 ou mais produtos//
if(produto.selecionado == true && produto.selecionado >= 1){
  this.produtosMarcados.push(produto);
} 
   this.venda.produtos = this.produtosMarcados;
   console.log(this.venda.produtos);
}

//Capturo a descricao do item e os valores//
//Capturo a descricao dos produtos, funciona perfeitamente//
var i: any;
for (i=0; i < this.venda.produtos.length; i++){
  console.log("Os produtos são " +this.venda.produtos[i].descricao);
}

//Capturo o preço de cada item, funciona perfeitamente//
var v: any;
for (v=0; v < this.venda.produtos.length; v++){
  console.log("Os valores são " +this.venda.produtos[v].preco);
}

After this choice button I need to put on the screen the total value of the sale, where I need to add each position of the array.

2 answers

1

  • This way even for sure, but I can only get the output of the item in position[1]. So it doesn’t perform the sum, it displays only the value of the item [1] Até li sobre o reduce, but I still haven’t been able to implement it correctly.

  • I thank everyone for their help. This part is solved, now I’m only with another problem, but I made another post. Thanks

1

I agree with Bruno Soares, where Reduce is the best solution for the sum. But from what I understand, in the variable this.venda.products you have an array of objects.

This way you can map to make this object array into an array of values and then use reduce to add those values.

Example:

var produto = [{preco: 1}, {preco: 2}];

console.log(produto.map((prod) => prod.preco).reduce((total, preco) => total + preco));
  • That’s right, thank you very much. Now I ask you a question, instead of the {price: 1} I need to put the dynamic value, in case the item price, for example 10,00 or 15,00. How do I do this replacement ?

  • I do not know if I understood your question correctly, but looking at your initial code all the information you need (products and prices) is not in this.venda.products? If so, all you have to do is replace the product variable I put with yours and it’s there.

  • I managed to Resolve Francisco, thank you so much for your help. It all worked out

Browser other questions tagged

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