JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to remove null values from an array in JavaScript?

To remove null values from an array, you must follow the following steps:

  1. Call the filter() method on the array from which you want to remove null values.
  2. Inside the callback function of the filter() method, compare each array value to null.
  3. If the array element is null, then return false. Here, false means that array element won't become part of the new array.
let shoppingList = ['Apples', 'Milk', null, 'Bread', null, "Biscuits", null];
let result = shoppingList.filter(element => {
  if(element !== null){
    return true;
  }else{
    return false;
  }
});

console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]

Note: It is important to note that the filter() method does not modify the original array. Instead, it returns a new array whose elements satisfy the condition.

If you don't want to use the filter() method, then you can use the forEach() method.

To remove null values from an array using the forEach() method, you must follow the following steps:

  1. First, create an empty array that will hold array elements that are not null.
  2. Call forEach() method on the array from which you want to remove null values.
  3. Inside the forEach() method, check if the current processing element is not equal to null. If the condition is satisfied, push that array element into the empty array created in step 1.
let result = [];
let shoppingList = ['Apples', 'Milk', null, 'Bread', null, "Biscuits", null];

shoppingList.forEach(element => {
  if(element !== null){
    result.push(element)
  }
});

console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]

Recommended Posts