We will learn to How to remove null and falsy in JavaScript array with code examples. “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. That is, all values are truthy except false
, 0
, -0
, 0n
, ""
, null
, undefined
, and NaN
.”
1. Boolean Constructor to remove null and false in JavaScript string array
The Javascript array. filter() is a standard built-in function of the array it returns a new array with all elements which passed the condition implemented by a callback function. The array. filter() runs a callback function for each array element. if the callback function returns true the array element includes in the return result array.
const strArr = ['dev', null, 'enum', null, 'c',false];
var myFilterArray = strArr.filter(Boolean);
console.log(myFilterArray)
Output
[ 'dev', 'enum', 'c' ]
2. !! expression How to remove null and false in JavaScript string array
In this example, we have removed Falsy using the !! expression by using the Array.filter() method.We have defined a function name checkfalse() that takes an array as input and prints the result.
const strArr = [1, 2, null, null, 'c',false];
function checkfalse(arr) {
return arr.filter(function(item) { return !!item; });
}
console.log(checkfalse(strArr))
Output
[ 1, 2, 'c' ]
3. Arrow function to remove null and false in JavaScript string array
In the below example, we have used the array.filter() function and filter the non-falsy values using the arrow function and return the result
const strArr = [1, 2, null, null, 'c',false,'Dev'];
var result = strArr.filter((item) => {return Boolean(item) === true })
console.log(result)
Output
[ 1, 2, 'c' ]