0

I would like to explain my problem of the day.

currently i map, everything works correctly

my problem and that I wish I could create a div in it in order to display the result of total , unfortunately I can't

Do you have an idea of how to fix this?

 {this.props.items.map(item => { 
 const product = this.props.items;
 let total = 0;

 console.log(total)
 console.log('yolo',product)
 console.log('yolo array',product[0].quantity)

for (let i = 0 ; i<product.length;i++){
console.log('products',product[i].quantity) 
total = total + product[i].quantity;                        
}
} 
)}
talex
  • 17,973
  • 3
  • 29
  • 66
Neff
  • 199
  • 2
  • 17
  • Does this answer your question? https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers – keikai Mar 06 '20 at 10:46

1 Answers1

1

even if you were to render something using total, with this method you would render a "total item" for each item in props.items. What you want to use here is the reduce method. Here is an example with a very basic div, but you can decide what to render in place of it

<div>
{this.props.items.reduce((total,item) => item.quantity + total, 0)}
</div>

What the reduce methos does is returning a single value from a list of elements. The second parameter is your initial value, while he first is the callback that will be executed at each iteration