Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
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.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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!

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda