Remove null, undefined and empty values from array in JavaScript

Total
0
Shares
remove null, undefine and empty values from array in javascript

In this article we are going to learn how to remove null, undefined and empty values from array in Javascript. We get null or undefined values in array when we either delete the index or add some value at bigger index than the length of array. We will use ES6 format in our codes.

Code to remove null from array

This code will only remove the null values from given array.

const removeNullFromArray = (arrayToClean) => {
  const cleanedArray = [];
  arrayToClean.forEach((val) => {
    if(val !== null){
      cleanedArray.push(val);
    }
  });

  return cleanedArray;
}

var myArray = [5,6,,7,8];
myArray = removeNullFromArray(myArray);

In this code, we have created a function removeNullFromArray(). This will accept one parameter, i.e. your array. It runs a forEach loop to check if the array value is not equals (!==) to null. Accordingly it pushes the value into a temporary array cleanedArray and return it.

You may also like –

Code to remove undefined from array

The below code will only remove the undefined values from array.

const removeUndefinedFromArray = (arrayToClean) => {
  const cleanedArray = [];
  arrayToClean.forEach((val) => {
    if(typeof val !== "undefined"){
      cleanedArray.push(val);
    }
  });

  return cleanedArray;
}

var myArray = [5,6,undefined,7,8];
myArray = removeUndefinedFromArray(myArray);

In this code we have used the typeof function of javascript. This can simply check if a value is undefined or not. Accordingly, we can push it in our temporary array and return.

Why didn’t we use typeof to check null?

Because, since the beginning of JavaScript typeof null is equals to object. You can read more about it here.

Code to remove empty values from array

This code will only remove empty values from array.

const removeEmptyValueFromArray = (arrayToClean) => {
  const cleanedArray = [];
  arrayToClean.forEach((val) => {
    if((""+val).trim() !== ""){
      cleanedArray.push(val);
    }
  });

  return cleanedArray;
}

var myArray = [5,6,'',7,8];
myArray = removeEmptyValueFromArray(myArray);

Here we are checking if a value is blank or not using val.trim() !== "". If it is blank then we won’t push it into our temporary array.

Final Code

In this code, we will merge our functionality of removing null, undefined and empty values. This can be used to remove all kinds of undesired values.

const removeNullUndefinedEmptyFromArray = (arrayToClean) => {
  const cleanedArray = [];
  arrayToClean.forEach((val) => {
    if(val !== null && typeof val !== "undefined" && (""+val).trim() !== ""){
      cleanedArray.push(val);
    }
  });

  return cleanedArray;
}

var myArray = [5,6,'',,undefined,7,8];
myArray = removeNullUndefinedEmptyFromArray(myArray);

    Tweet this to help others

You may also like –

Live Demo

Open Live Demo