- 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
Filtering out only null values in JavaScript
We are required to write a JavaScript function that takes in an array that contains some false values. The function should remove all the null values from the array (if there are any) in place.
For example: If the input array is −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null];
Then the output should be −
const output = [12, 5, undefined, 0, false, 67, undefined, false];
Example
The code for this will be −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null]; const removeNullValues = arr => { for(let i = 0; i < arr.length; ){ // null's datatype is object and it is a false value // so only falsy object that exists in JavaScript is null if(typeof arr[i] === 'object' && !arr[i]){ arr.splice(i, 1); }else{ i++; continue; }; }; }; removeNullValues(arr); console.log(arr);
Output
The output in the console −
[ 12, 5, undefined, 0, false, 67, undefined, false ]
Advertisements