Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Total price of items in Cart react

I wanted to get total sum of all items in the cart page based on their qty. Algorithm that i used is incorrect because it is not calculating sum of each item with its qty, but sum of all item price and sum of all item qty. Can anyone help how to calculate each item price with its qty and sum it up with all item prices ? Here is the source code:

 let totalQty = 0;
 let totalSum = 0;
 let newArr = [];
    
this.props.cart.map(item => {
        totalQty += item.qty
        item.prices.filter(price => price.currency.symbol === this.props.symbol)
      .map(price => newArr.push(price.amount))
       }) 
    totalSum = newArr.reduce((acc, val)=> (acc + val*totalQty), 0)
    let tax = this.props.formatNumber({ value: totalSum*(21/100), digitCount: 0 }) 

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just push the subtotal for each item into newArr instead then sum up at the end

let totalQty = 0;
let totalSum = 0;
let newArr = [];
    
this.props.cart.map(item => {
  totalQty += item.qty
  item
    .prices
    .filter(price => price.currency.symbol === this.props.symbol)
    .map(price => newArr.push(item.qty * price.amount))
}) 
totalSum = newArr.reduce((acc, val)=> (acc + val), 0)
let tax = this.props.formatNumber({ value: totalSum*(21/100), digitCount: 0 })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading