Skip to content

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

Answer

You can use the ternary operators instead

return arr.flatMap((f) => f === null ? [] : f);