Over here, we will be discussing how to remove the null values from an array given through JavaScript. In fact, there are many ways to solve this problem and achieve an array without any null values. In this section we will discuss the removal of null values using filter function which is built-in.
Using the filter Method
By using the filter method, the null values are easily eliminated. It takes array as an input and outputs an array with no null values.
Detailed Procedures
1. Create an array in such a way that it contains values which are null and not null.
2. Now make use of the filter method and remove all the null values present in the array.
3. Once the function ends, it provides the array with no null values.
Example Program
Let’s see the example usage of the method filter in removing the null values from the array
// Step 1: Create an array with some null values let arrWithNull = [1, null, 2, null, 3, null, 4, 5, null]; // Step 2: Use the filter method to remove null values let arrWithoutNull = arrWithNull.filter(function(ele) { return ele !== null; }); // Step 3: Log the result to the console console.log(arrWithoutNull);
Explanation of the Code
Creating an array: Create an array named arrWithNull that contains integers and null values. Filter Null Values: Call the filter method on arrWithNull. Provide a function to filter that checks if each element is not null. Include elements that are not null in a new array named arrWithoutNull.
Output
The output of the above code is
[1, 2, 3, 4, 5]