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);2console.log(firstApproach);3// ['1', 2, 'Three']4
2. Approach 2 - with filter(Boolean)
1const secondApproach = arrayToFilter.filter(Boolean);2console.log(secondApproach);3// ['1', 2, 'Three']4
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!