Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda