Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Filter null from an array in JavaScript?
To filter null values from an array in JavaScript, use the filter() method. This method creates a new array containing only elements that pass a specified condition.
Syntax
array.filter(callback)
Method 1: Using Boolean Constructor
The simplest approach is to pass Boolean as the filter callback, which removes all falsy values including null, undefined, and empty strings.
var names = [null, "John", null, "David", "", "Mike", null, undefined, "Bob", "Adam", null, null];
console.log("Before filtering:");
console.log(names);
var filteredNames = names.filter(Boolean);
console.log("After filtering null/falsy values:");
console.log(filteredNames);
Before filtering: [ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 'Adam', null, null ] After filtering null/falsy values: [ 'John', 'David', 'Mike', 'Bob', 'Adam' ]
Method 2: Filtering Only null Values
If you want to keep other falsy values like empty strings but remove only null and undefined, use a specific condition:
var data = [null, "John", null, "David", "", "Mike", null, undefined, "Bob", 0, false, "Adam"];
console.log("Original array:");
console.log(data);
var filterOnlyNull = data.filter(item => item !== null && item !== undefined);
console.log("After filtering only null and undefined:");
console.log(filterOnlyNull);
Original array: [ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 0, false, 'Adam' ] After filtering only null and undefined: [ 'John', 'David', '', 'Mike', 'Bob', 0, false, 'Adam' ]
Comparison of Methods
| Method | Removes null | Removes undefined | Removes empty strings | Removes 0/false |
|---|---|---|---|---|
filter(Boolean) |
Yes | Yes | Yes | Yes |
filter(item => item !== null) |
Yes | No | No | No |
filter(item => item != null) |
Yes | Yes | No | No |
Key Points
-
filter(Boolean)removes all falsy values (null, undefined, "", 0, false, NaN) - Use strict comparison (
!== null) for precise filtering - The
filter()method returns a new array without modifying the original - Loose equality (
!= null) removes both null and undefined
Conclusion
Use filter(Boolean) for removing all falsy values, or filter(item => item !== null) for removing only null values. Both methods create clean arrays without null elements.
Advertisements
