Skip to content
Advertisement

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:

JavaScript

For example:

JavaScript

However, I realized that it also removes undefined values.

JavaScript

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:

JavaScript

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

Advertisement

Answer

You can use the ternary operators instead

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement