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

132
Visualizações
if checks inside a reduce() sum function

I am trying to iterate through an array in typescript, but on occasion, inside the array there will be an empty value or NaN (null) value by default. this really mucks up my sum function, as it is trying to call parseInt() on a null value, so the function also returns NaN. How can I make an if condition inside of this function to check for Number() first otherwise skip/continue ? I know I can naively have a for each loop, and check for this inside of an if statement, but that is not ideal.

    sumOwnershipLiabilityPercentages(): number{
        // return the sum of all the percentage ownerships
        return this.liabilitiesOwnershipList.reduce((prev: number, cur: any) => prev + parseInt(cur.percentage), 0);
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can make the summation conditional.

const sum = d.reduce((p: number, c: number) => p += (c) ? c : 0)

if you want to make a more elaborate if statements do it like so

const sum2 = d.reduce((p: number, c: number) => {
   if (c)
      return p += c;
   else
      return p += 0;
   })

or, in your case, something like this

return this.liabilitiesOwnershipList.reduce((prev: number, cur: any) => {
    if (cur && cur?.percentage)
      return prev += parseInt(cur.percentage);
    else
      return prev += 0;
  });
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