const clean = arr.filter(item => !!item || item === 0 || item === false);
Enter fullscreen mode
Exit fullscreen mode
...
For further actions, you may consider blocking this person and/or reporting abuse
Interesting is that all these filtered can be coerced to false, and only the number 0 and
false
can, too. That would simplify the filter to:EDIT: The original article did something like:
Now that it is updated, the above doesn't seem to make sense, obviously.
Hi,
thank you for the simplification! I updated the article and the code.
Cheers!
Next time I suggest posting an edit rather than overwriting the old article. The comment above makes no sense given the new article context.
Why not just this?
Ah, I misread - you want to keep
0
andfalse
. In which case, you can shorten to:The
!!
is unnecessary.Because it was explicitly stated that
false
and0
should not be filtered. Your code would filter them.Why we would like "" from string list? "" and 0 is give false result but each means something.
Hi Peter,
I can not exactly follow you train of thought. Would you mind to elaborate a bit?
Thank you !
Empty string is something, not nothing. This kind of thinking is paramount in, for example, shell scripting/programming, where whether a string is null or simply doesn't exist changes everything about the command
Can be achieved with a very short statement: arr.filter(Boolean).
The comment by @lexlohr should also be regarded if we don't want to filter out values such as 0 or false.
Shorter than
arr.filter(Boolean)
isarr.filter(i=>i)
Hi Damjan,
thank you for the suggestion. Indeed, this function should preserve 0 and false. Array.filter(Boolean) will be another oneliner which removes everything that is considered "false".
Cheers!