How to Remove All Falsy Values From a JavaScript Array?

Quick tip to filter out falsy values from a JavaScript array

To remove all falsy values from a JavaScript array, you can simply iterate over each element of the array and test if it is falsy or truthy by casting it to boolean. Some ways in which you can do this are explained as follows:

Using Array.prototype.filter()

In ES5+, you can use the Array.prototype.filter() method to remove all falsy values. All you have to do is return boolean true for values you wish to keep in the resulting array, and return boolean false for the ones you wish to exclude. To do that, for example, you can simply use double negation to cast truthy values to boolean true and falsy values to boolean false like so:

// ES5+
const arr = [0, '', null, 1, NaN, false, 2, 3, undefined, 5];

const filteredArr = arr.filter(function (value) {
    return !!value;
});

console.log(filteredArr); // output: [1, 2, 3, 5]

Or alternatively, you can use the arrow function syntax (introduced in ES6) for a one-liner like so:

// ES6+
const arr = [0, '', null, 1, NaN, false, 2, 3, undefined, 5];

const filteredArr = arr.filter((value) => !!value);

console.log(filteredArr); // output: [1, 2, 3, 5]

You may shorten it even further by using the Boolean object like so:

// ES6+
const arr = [0, '', null, 1, NaN, false, 2, 3, undefined, 5];

const filteredArr = arr.filter(Boolean);

console.log(filteredArr); // output: [1, 2, 3, 5]

This works because it is the equivalent to the following:

const filteredArr = arr.filter((value) => Boolean(value));

It's better to make your code more readable, so in most cases using arr.filter(Boolean) might not be a good choice.

Using for Loop

If you're unable to support a minimum ES5, then you can use a for loop to create a new array with filtered values. For example:

const arr = [0, '', null, 1, NaN, false, 2, 3, undefined, 5];
const filteredArr = [];

for (let i=0; i<arr.length; i++) {
    if (!!arr[i]) {
        filteredArr.push(arr[i]);
    }
}

console.log(filteredArr); // output: [1, 2, 3, 5]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.