Remove empty elements from an array in Javascript
Eager to clean up your array? Use filter(Boolean) to dust off those falsy items. A falsy item could be "",null, undefined, false, 0, or even NaN.
Quick scan of methods and use-cases
Sometimes plain boolean filtering doesn't suffice. Certain scenarios require special attention. So, let's do a quick stroll through some handy recipes.
Keeping zeroes
In the world of Boolean, 0 is an outcast. You might often want to include 0 in your array.
Allow everyone but null & undefined
Maybe 0 and false are your buddies but null & undefined are your persona non grata. Check this out:
Getting strings in shape
Strings, especially with whitespaces or newline characters, need a pre-cleanup:
Filling up the sparse
Sparse arrays are annoyingly laced with empty slots. Get them in shape:
Manual filtering
For full control, do a manual cleanup:
Worth noting and troubleshooting
On your marks, get set, optimize!
When working with large arrays, always keep an eye out for the performance. Remember, filter spawns a new array, and that carries a cost.
Keep conflicts at bay
A word of caution, stay away from extending Array.prototype. It might stir up conflicts in your code.
Library magic
If you're a fan of Underscore.js or Lodash, _.compact(array) could be your magic wand.
Old is gold
Programmers are cool, but some of us still need to support older browsers. For them, have a polyfill for Array.filter().
Was this article helpful?