Search code examples
reactjssum

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


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 })