Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 8, 2020 02:15 am GMT

Cool trick to filter undefined values from an array in Javascript

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!


Original Link: https://dev.to/austinblade/cool-trick-to-filter-undefined-values-from-an-array-in-javascript-4oi3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To