const clean = arr.filter(item => !!item || item === 0 || item === false);
Returns a new array without empty strings
, NaN
, null
, undefined
items.
The repository & npm package
You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.
The code and the npm package will be updated every time I publish a new article.
Follow me on Twitter: @martinkr and consider to buy me a coffee
Photo by zoo_monkey on Unsplash
Top comments (12)
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!