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

226
Visualizações
Javascript - use redcuce to calculate total cost in array

I have an array with items. Each of these items have the following values

invoice_rows: [
  { item: '', qty: '', price: '' }
],

For each invoice item there is a row added to the array but I want to get the total cost of all these items. So let's do some math, I have the following array with data

invoice_rows: [
  { item: 'item1', qty: '4', price: '10' }
  { item: 'item2', qty: '2', price: '10' }
  { item: 'item3', qty: '5', price: '5' }
],

The total cost should be the sum of the qty * price for each row. Making the total 40 + 20 + 25 = 85. How can I do this with the reduce method?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

const invoice_rows = [
  { item: 'item1', qty: '4', price: '10' },
  { item: 'item2', qty: '2', price: '10' },
  { item: 'item3', qty: '5', price: '5' },
];

const initialValue = 0;
const sumWithInitial = invoice_rows.reduce(
  (previousValue, currentValue) => previousValue + currentValue.qty*currentValue.price,
  initialValue
);

console.log(sumWithInitial);
about 4 years ago · Juan Pablo Isaza Relatório

0

Given

const invoice_rows = [
  { item: 'item1', qty: '4', price: '10' }
  { item: 'item2', qty: '2', price: '10' }
  { item: 'item3', qty: '5', price: '5' }
];

simply first calculate qty * price using map for all items, then add the subtotals:

const total = invoice_rows.map(item => item.qty * item.price).reduce((a, b) => a + b, 0);

note that JS will implicitly cast '4' * '10' to the the number 40.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do:

const invoice_rows = [
  { item: 'item1', qty: '4', price: '10' },
  { item: 'item2', qty: '2', price: '10' },
  { item: 'item3', qty: '5', price: '5' }
]

const result = invoice_rows.reduce((a, { qty, price }) => a + qty * price, 0)

console.log(result)

about 4 years ago · Juan Pablo Isaza 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