0

I have online shopping app in react .I have Invoice array called invItems and products called items in that array. I want to calculate the price*quantity of all the items in invItems array. moreover I want to calculate the total quantity of all object (items) in the invoice. the code is give as below:

useEffect(()=>{
if(invItems.length>0){
  var invtotal=0.0;
  var total=invItems.reduce((invTotal,x)=>(invTotal+=x.total));
  var sum=0;
   sum=invItems.reduce((sum,x)=>(sum+=x.qty));
  console.log("result:",total,sum );
}
  
},[invItems])
console.log("invItems:",invItems);

each Item is object as below:

const newItem={
    OId:'',
    productId: '',
    productName: '',
   productCode: '',
    qty:1,   
    price: 0.0,
    total:0.0,
}

the result is not correct or in correct form please see the console in screenshots.result console screenshot

invItems screenshot

Fiaz Ahmed Ranjha
  • 245
  • 1
  • 6
  • 22
  • Does this answer your question? [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – tr05t Aug 12 '21 at 10:54

1 Answers1

0

I am sharing so that it may be helpful for anyone. following changes solved my problem.it calculates the total and qty of all invItems.

useEffect(()=>{
if(invItems.length>0){
  var invtotal=0.0;  //(a,v)=>a+v.credit,0
  var total=invItems.reduce((a,x)=>a+x.total,0);
  var sum=0;
   sum=invItems.reduce((a,x)=>a+x.qty,0);
  console.log("result:",total,sum );
}
  //setVal({...val,total:total,qty:qty})
},[invItems])

best regards

Fiaz Ahmed Ranjha
  • 245
  • 1
  • 6
  • 22