const cleanFalsy = arr => arr.filter(Boolean);
Optimised version:
const cleanFalsy = arr => arr.filter(i=>i);
Returns a new array without all items which are considered to be "false" (0, '', Nan, false, undefined, null).
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 (2)
This is almost twice as fast on Firefox. On Chrome, the two methods are similarly efficient with
i=>i
being ever so slightly quicker. Performance linkI guess this is because allowing the internal Boolean coercion to do its thing is faster than explicitly doing it yourself.
Thank you for the effort of setting up the performance comparison and sharing with us. I amended he article on updated the code.
Cheers!