- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ]
Advertisements