Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!