Explain Codes LogoExplain Codes Logo

Remove empty elements from an array in Javascript

javascript
filter
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Mar 4, 2025
TLDR

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.

const unfilteredArray = [1, "", null, 2, undefined]; const cleanArray = unfilteredArray.filter(Boolean); // [1, 2], as clean as my room on laundry day.

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.

// Don't leave out 0 in the cold. Welcome it back const arrayWithZeros = [0, 1, null, 2, 0].filter(e => e === 0 || e); // [0, 1, 2, 0]

Allow everyone but null & undefined

Maybe 0 and false are your buddies but null & undefined are your persona non grata. Check this out:

// When "null" sounds nullifying and "undefined" equals "unwanted" const noNullArray = [0, 1, null, 2, undefined].filter(el => el != null); // [0, 1, 2], null & undefined who?

Getting strings in shape

Strings, especially with whitespaces or newline characters, need a pre-cleanup:

// " " and "\n", you might be 'strings' but sorry, no place for you. const stringArray = ['text', '\n', ' '].map(s => s.trim()).filter(Boolean); // ['text']

Filling up the sparse

Sparse arrays are annoyingly laced with empty slots. Get them in shape:

// Literally, render the space. But, in a good sense. const sparseArray = [1, , , 2, 3]; const denseArray = sparseArray.filter(() => true); // [1, 2, 3]

Manual filtering

For full control, do a manual cleanup:

let arr = [0, 1, false, 2, '', 3]; let newArr = []; // Just like my closet on a Sunday cleaning spree. Only clothes that fit, stay! for(let i = 0; i < arr.length; i++) { if(arr[i] || arr[i] === 0) { newArr.push(arr[i]); } } // newArr is [0, 1, 2, 3] and sparkling clean ;)

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.

const _ = require('underscore'); // Let's get compact ;) const compactArray = _.compact([0, 1, false, 2, '', 3]); // Here you go [1, 2, 3].

Old is gold

Programmers are cool, but some of us still need to support older browsers. For them, have a polyfill for Array.filter().