Home > Back-end >  Total price of items in Cart react
Total price of items in Cart react

Time:08-29

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

CodePudding user response:

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

CodePudding user response:

try this :

const totalAmount = this.props.cart.reduce((acc,curr)=>{
   return curr.qty*curr.price   acc
},0)

CodePudding user response:

Just use reduce on totalQty to calculate the count, and reduce totalSum to get qty * amount

let totalQty = this.props.cart.reduce((acc, item) => acc   item.qty, 0)
let totalSum = this.props.cart.reduce((acc, item) => {
    const price = item.prices.find(price => price.currency.symbol === this.props.symbol)
    if (price) {
        acc  = (price.amount * item.qty)
    }
    return acc
}, 0)
  • Related