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

93
Views
How to drop null elements but not undefined when using `arr.flatMap((f) => f ?? [])`?

I've written a function that removes null values from an array:

const dropNull = <T,>(arr: T[]): T[] => {
    return arr.flatMap((f) => f ?? []); // depends >= ES2019
};

For example:

const myArr1 = ['foo', 'bar', 'baz', null]
const output1 = dropNull(myArr1) 
console.log(output1) // => ["foo", "bar", "baz"] 

However, I realized that it also removes undefined values.

const myArr2 = ['foo', 'bar', 'baz', null, undefined]
const output2 = dropNull(myArr2)
console.log(output2) // => ["foo", "bar", "baz"] 

Is there a way to just tweak the current dropNull() in order to remove null but not undefined? That is, I know I could have re-written the function as:

const dropNull2 = <T,>(arr:T[]): T[] => {
    return arr.filter(element => element !== null)
}

But I like the arr.flatMap((f) => f ?? []) style. Is there a small change to it so it will drop only null but not undefined?

TS playground

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use the ternary operators instead

return arr.flatMap((f) => f === null ? [] : f);
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!