Skip to content
Advertisement

Return no element from `Array.flatMap()` by if condition

I have this code:

JavaScript

The above code used a ternary operator of condition ? exprIfTrue : exprIfFalse.

Currently I’m returning empty objects of { } in the case of exprIfFalse.

How can I return nothing in the case of exprIfFalse? I mean, I want absolutely nothing. I mean no array element.

Advertisement

Answer

Why cant you just return an empty array, any how Array.flat will remove those empty array from final code. In your case the array is not empty as [], its an array with two empyty objects as [{}, {}] that will produce two empty objects {}, {} in the final output after Array.flat

You have to return something from flatMap. If you return nothing, the corresponding nodes will be added as undefined. That wont be removed with Array.flat. Best option is to return an empty array as below.

Pseudo Code

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