Corey King
Corey King

Reputation: 13

How do I calculate the total of multiple items?

I am trying to get a total of price of all the items multiplied by the quantity of the item:

const shoppingCart = {
    "tax": .08,
    "items": [
        {
            "title": "orange juice",
            "price": 3.99,
            "quantity": 1
        },
        {
            "title": "rice",
            "price": 1.99,
            "quantity": 3

The result I want to get is 9.96. But I'm struggling to come up with a proper way to do so.

Upvotes: 1

Views: 492

Answers (1)

long_hair_programmer
long_hair_programmer

Reputation: 580

Using a for loop

let totalPrice = 0

shoppingCart.items.forEach(item => {
  totalPrice += item.price * item.quantity
})

But in JS it's also useful to get used to different iterators such as reduce. It may appear a bit confusing at first but basically it just loops through the array, applies some logic (that we can add) and returns a single value which is perfect for computing sum.

const totalPrice = shoppingCart.items.reduce((total, item) => total + (item.price * item.quantity), 0)

Hope it helps!

Upvotes: 3

Related Questions