Thu Jun 02 2022

How to remove falsy elements/values from a JavaScript Array

Here are some of the best ways to remove falsy values from a JavaScript array

Here are some of the ways in which I filter falsy values from arrays in my daily work. When I find more, I'll add them over here.

Here is the array that we need to remove falsy values from

1const arrayToFilter = ["1", 2, "Three", false, null, undefined, "", NaN, 0, -0];

1. Approach one - with filter(x=> x)

1const firstApproach = arrayToFilter.filter((x) => x);
3// ['1', 2, 'Three']

2. Approach 2 - with filter(Boolean)

1const secondApproach = arrayToFilter.filter(Boolean);
3// ['1', 2, 'Three']

Did this help you or do you have any other ways of filtering falsy values out in JavaScript? Hit me up in the comments and let me know!