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

328
Visualizações
Calculating sum of array objects in javascript , TypeError: parseInt(...).reduce is not a function

I have a array of objects with numbers but there type is string , I want to sum them all.

enter image description here

I'm doing this way as of previous answers on stack-overflow suggested.

// Here the data has an array of goods which contains
// amount objects and i want to calculate to sum of amount objects
Total Invoice Price:
{data.goods
   ? data.goods.map((item) => (
    <div key={item.id}>
     <div>{parseInt(item.amount).reduce((a, b) => a + b, 0)}</div>
       </div >
       ))
     : null}

But im getting error TypeError: parseInt(...).reduce is not a function , How to fix this ?

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

0

reduce is an array method. So: instead of mapping over the data, call a function within your JSX that returns the sum of the amount values of each object in the array.

Note: if your amount values are strings coerce them to numbers first (Number(good.amount)).

function Example({ data }) {

  function getTotal(data) {
    return data.goods.reduce((acc, good) => {
      return acc + Number(good.amount);
    }, 0);
  }

  return (
    <div>
      <h4>Total</h4>
      <p>{getTotal(data)}</p>
    </div>
  );

}

const data = { goods: [{ amount: '1' }, { amount: '5' }, { amount: '13' }] };

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

goods = [{
    amount: "11"
  },
  {
    amount: "11"
  },
  {
    amount: "11"
  },
]

let sum = goods.reduce((a, b) => a + parseInt(b.amount), 0)

console.log(sum)

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