DEV Community

loading...
Cover image for Cool trick to filter undefined values from an array in Javascript

Cool trick to filter undefined values from an array in Javascript

austinblade profile image Austin Blade ・2 min read

For the longest time, I have used this method to filter out undefined/null values from arrays in JS.

const filteredArray = arrayToFilter.filter(x => x !== undefined);
Enter fullscreen mode Exit fullscreen mode

I came across a similar situation not too long ago where someone needed to filter undefined objects from an array and used this mysterious syntax to do so..

const filteredArray = arrayToFilter.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

It works! But why does it work exactly?

Let's break it down piece by piece.

How does .filter work?

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

So for the first example, if x !== undefined, the object becomes part of the new array. If x === undefined, it is left out of the new array.

The filter is using a function that returns true or false. If the result of the function is true, then the value is added to the new array.

Truthy and Falsy Explained

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN).

What's important to remember here is that undefined is a falsy.

The Boolean function

A JavaScript Boolean represents one of two values: true or false.

You can use the Boolean() function to find out if an expression (or a variable) is true:

Boolean(10 > 9)        // returns true 
Enter fullscreen mode Exit fullscreen mode

Instead of passing in an expression, lets see what happens when we only pass in a value.

Boolean(10)        // returns true 
Enter fullscreen mode Exit fullscreen mode

Why did that return true? Because 10 is a truthy value. It is not false, 0, -0, 0n, "", null, undefined, or NaN.

So, if we pass in a falsy value:

Boolean(undefined)        // returns false 
Enter fullscreen mode Exit fullscreen mode

Now let's piece it all together.

undefined is a falsy value. Passing a falsy value into the Boolean function would return false. Since the function returns false, the value is not added to the new array. If any other truthy value is passed into the Boolean function, the function returns true, and that value is added to the new array.

So the next time you need to filter out undefined values from an array, save yourself some time and use the Boolean function to do the work for you!

Discussion (13)

pic
Editor guide
Collapse
rajmohanpdy profile image
rajmohan selvaraj

useful info. thanks for sharing.

const arr = [1, 2, 3, 4, 5, 6, 7, 8, undefined, null, 0, "", -0];
//i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN

const filter = arr.filter((x) => Boolean(x));
console.log(filter); // [1, 2, 3, 4, 5, 6, 7, 8]

Collapse
austinblade profile image
Austin Blade Author

It's good to point out that the 0 is removed in the example you provided! (I should have included that in this post as a precaution). Wouldn't want to use this method on an array of numbers if you expected 0 to be in there. Thanks for sharing that!

Collapse
lucassperez profile image
Lucas Perez

If we want to keep the zeros we can first check if the value is 0 and then use the Boolean. Like this:
const array = [ 0, 1, 2, undefined, 4, NaN, "" ]
array.filter( x => x === 0 || Boolean(x) )

The output is going to be
[ 0, 1, 2, 4 ]
😁

In fact we can use the Boolean and then check if it is === 0, but that's the idea.

Thread Thread
austinblade profile image
Austin Blade Author

When you put it that way, it is still good for something if you have 0 in the array. 🙂

Collapse
pengeszikra profile image
Peter Vivo
[0, null, undefined, 3, 55, "", []]
  .filter( item => (item ?? false) !== false );

// -> [0, 3, 55, "", Array(0)]
Enter fullscreen mode Exit fullscreen mode
Collapse
austinblade profile image
Austin Blade Author

Very cool use of a coalesce 👍🏻 Smart!

Collapse
sergeypodgornyy profile image
Sergey Podgornyy
const arrayToFilter = [0, 1, 2, 3, 4, undefined];
const filteredArray = arrayToFilter.filter(Boolean);

console.log(filteredArray);
// 1, 2, 3, 4
Enter fullscreen mode Exit fullscreen mode

Any you fucked up your data 🤷‍♂️ as 0 is also false for Boolean, like many other things. If you want to check for undefined, you have to always use explicit solution with

const filteredArray = arrayToFilter.filter(x => x !== undefined);
Enter fullscreen mode Exit fullscreen mode

No other choice

Collapse
austinblade profile image
Austin Blade Author

Thanks for your comment, Sergey! You're absolutely right. I have another comment on here saying I should have been more explicit with a warning like that in the article.

Collapse
iminside profile image
Dan Chu

By the way, only numbers can be left like this.

[1, 2, 3, 4, 5, undefined, null, "hi guys", 0].filter(Number.isInteger)
// [1, 2, 3, 4, 5, 0]
Enter fullscreen mode Exit fullscreen mode
Collapse
jonrandy profile image
Jon Randy
const filteredArray = arrayToFilter.filter(x=>x)
Enter fullscreen mode Exit fullscreen mode

Will do exactly the same as your 'trick', and is shorter

Collapse
austinblade profile image
Austin Blade Author

🤯 I’ve never seen that before! Can you explain why that works?

Collapse
jonrandy profile image
Jon Randy

You answered this yourself in "Truthy and Falsy explained"

Thread Thread
austinblade profile image
Austin Blade Author

Ahh I see now. That went right over my head for a second. 🙃