DEV Community

Cover image for 1 line of code: How to clean an Array of  "falsy" items
martin krause
martin krause

Posted on

1 line of code: How to clean an Array of "falsy" items

const cleanFalsy = arr => arr.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

Optimised version:

const cleanFalsy = arr => arr.filter(i=>i);
Enter fullscreen mode Exit fullscreen mode

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


Discussion (2)

Collapse
jonrandy profile image
Jon Randy • Edited on
const cleanFalsy = arr => arr.filter(i=>i)
Enter fullscreen mode Exit fullscreen mode

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 link

I guess this is because allowing the internal Boolean coercion to do its thing is faster than explicitly doing it yourself.

Collapse
martinkr profile image
martin krause Author

Thank you for the effort of setting up the performance comparison and sharing with us. I amended he article on updated the code.

Cheers!