Remove Null Values From an Array in JavaScript

In arrays, removing null values (including empty strings, null, undefined, and so on) is an important task for developers. To do so, JavaScript provides some methods, such as a traditional for loop that will iterate the array and add the values in a new array, the forEach() method, or the filter() method.

This post will illustrate the methods for removing null values from JavaScript arrays.

How to Remove Null Values From JavaScript Array?

  1. filter() method
  2. for loop
  3. forEach() method

1. Using the filter() Method

The filter() method is a straightforward way to remove null values from an array. It creates a new array with all elements that pass the test implemented by the provided function.

const array = [1, null, 2, null, 3, 4, null];
const filteredArray = array.filter(element => element !== null);

console.log(filteredArray); // Output: [1, 2, 3, 4]

Explanation:

array.list(element => element != =null)  iterates over each element in the array

The arrow function checks if the element is not null

If the condition is true, the element is included in the filteredArray

2. Using a for Loop

A for loop allows you to manually iterate over the array and push non-null values into a new array.

const array = [1, null, 2, null, 3, 4, null];
const resultArray = [];

for (let i = 0; i < array.length; i++) {
    if (array[i] !== null) {
        resultArray.push(array[i]);
    }
}

console.log(resultArray); // Output: [1, 2, 3, 4]

Explanation:

The for loop iterates through each element of the array.

The if condition check if the current element is not null.

If true, the element is pushed into resultArray.

3. Using the forEach() Method

The forEach() method iterates over each element in an array, allowing you to execute a function for each element.

const array = [1, null, 2, null, 3, 4, null];
const resultArray = [];

array.forEach(element => {
    if (element !== null) {
        resultArray.push(element);
    }
});

console.log(resultArray); // Output: [1, 2, 3, 4]

Explanation:

The forEach() method executes the provided function once for array element.

The if statement checks whether the element is not null.

Non-null elements are then pushed into resultArray.

 

Removing null values from an array in JavaScript can be accomplished using the filter() method, a for loop, or the forEach() method. Each approach is effective, but filter() is the most concise and is often preferred for its readability and simplicity.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top