Filter null from an array in JavaScript?


To filter null from an array and display only non-null values instead, use filter(). Following is the code −

Example

var
names=[null,"John",null,"David","","Mike",null,undefined,"Bob","Adam",null,null];
console.log("Before filter null=");
console.log(names);
var filterNull=[];
filterNullValues=names.filter(obj=>obj);
console.log("After filtering the null values=");
console.log(filterNullValues);

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo148.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo148.js
Before filter null=[
   null, 'John',
   null, 'David',
   '', 'Mike',
   null, undefined,
   'Bob', 'Adam',
   null, null
]
After filtering the null values=
[ 'John', 'David', 'Mike', 'Bob', 'Adam' ]

Updated on: 11-Sep-2020

866 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements