Nahid Islam
Nahid Islam

Reputation: 189

What is the best way of calculating the total amount (quantity*price) from the array of objects (State) in react?

I have an array of objects as my initial state like

const [product,setProduct]=useState([
    {
          id:1,
          product_title:"Item 1",
          quantity:2,
          price:100.00
    },
    {
          id:2,
          product_title:"Item 2",
          quantity:3,
          price:300.00
    },
])

Here I am also adding more items and at the same time, I Want to calculate the total amount based on quantity*price of each item from the objects. Right now I am proceeding with map() function like this code below and I am getting the exact result

const countTotal=(items)=>
{
     var total=0;
     product.map(item=>total+=item.quantity*item.price)
     setTotal(total)
}

Now My question is if it is a good process or there is an alternative way that is better and standard than this process.

Upvotes: 1

Views: 1237

Answers (2)

You are using .map method incorrectly, you should use reduce method instead, like this

const total = product.reduce((prev, cur) => {
  return prev + cur.quantity * cur.price;
}, 0);

Upvotes: 4

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22935

As a general rule, if you have array and want to single value based on all values, you need Array.proptotype.reduce()

const products = [
    {
          id:1,
          product_title:"Item 1",
          quantity:2,
          price:100.00
    },
    {
          id:2,
          product_title:"Item 2",
          quantity:3,
          price:300.00
    },
];
const countTotal = (items) => items.reduce((acc, curr) => acc + curr.quantity * curr.price, 0);

console.log(countTotal(products))

Upvotes: 3

Related Questions