How to remove falsy values from an array?

engrmahabub
Mahabubur Rahman
Published on Aug, 31 2023 1 min read 0 comments
image

How to remove falsy values from an array? 

The problem is we have an array and the array has some falsy values. So we need to remove the falsy values from the array. We can remove falsy value from an array by using Boolean in the filter function

// Remove falsy values from an array

let a =  ["fruit", false, "apple", NaN, 0,"banana", undefined, null, "mango", "", "oreng"]
// passing Boolean to array.filter() will remove falsy values from array

let fruits = a.filter(Boolean)

console.log(fruits)

["fruit", "apple", "mango", "oreng"]
VM1138:8 (5) ['fruit', 'apple', 'banana', 'mango', 'oreng']

 

Explanation:

We know Boolean(expression) in JS returns true/false. Let see the following expressions - 

Boolean(3 < 9)  // true
Boolean(100 > 111) // false
Boolean("man") // true
Boolean("") // false
Boolean(true) // true
Boolean(null)  // false
//Array example
let miscellaneous = [1,false,'a',Nan]
miscellaneous.filter(function(e){
return Boolean(e)
}) //  [1,'a']

OR 

miscellaneous.filter(Boolean) // [1,'a']

So we see the same result.

So this way we can remove all falsy values from an array.

 

 

0 Comments