ReactHustle

How to Remove Null or Empty Values from an Array in Javascript

Jasser Mark Arioste

Jasser Mark Arioste

How to Remove Null or Empty Values from an Array in Javascript

Using the Array.propototype.filter method #

There are multiple ways to remove null, undefined or empty values in javascript but I think the best and most concise is to use the filter() method as shown below.

//index.js

const arr = ['1', 2, , null, 4, 5, undefined, false];

const noEmptyValues = arr.filter((value) => value != null);

console.log(noEmptyValues); //["1", 2, 4, 5, false]
1234567

Why does this work? #

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Array.prototype.filter iterates through all the values of arr and executes a function we provided for each value, if the function returns true, then the value is retained, else it is removed.

I still don't understand how it works #

To understand how filter function works, let's try an alternative approach to filter the array using the good old for..loop statement.

// index.js

const arr = ['1', 2, , null, 4, 5, undefined, false];

const noEmptyValues = []

for(let i=0; i<arr.length; i++){
  let val = arr[i]; // get the value
  //check if value is null or empty
  if(val != null){
    //if not empty, push it to the new array
    noEmptyValues.push(val)
  }
}

console.log(noEmptyValues) //["1", 2, 4, 5, false]
12345678910111213141516

Refactoring the for..loop into our own filter function #

If we refactor this code and extract the if statement it would become like this:

//index.js
const arr = ['1', 2, , null, 4, 5, undefined, false];

const noEmptyValues = [];

//refactor so that the for loop state doesn't know the inner workings 
//of this function as long as it returns a boolean value
function predicateFunction(val){
  return val != null
}

for (let i = 0; i < arr.length; i++) {
  let val = arr[i];
  if (predicateFunction(val)) {
    noEmptyValues.push(val);
  }
}

console.log(noEmptyValues)  //["1", 2, 4, 5, false]
12345678910111213141516171819

If we refactor it further, we can create our own filter function:

#index.js

const arr = ['1', 2, , null, 4, 5, undefined, false];


function predicateFunction(val){
  return val != null
}



function myFilterFunction(array, testFunction){
  const newArray = [];
  for (let i = 0; i < array.length; i++) {
    let val = array[i];
    if (testFunction(val)) {
      newArray.push(val);
    }
  }
  return newArray
}

//notice how similar this looks to arr.filter(predicateFunction) or arr.filter(val => val!= null)
const filtered = myFilterFunction(arr, predicateFunction);

console.log(filtered)
1234567891011121314151617181920212223242526

This is all possible since in javascript, we can pass functions as first-class objects. If this was C++ or Java or OOP languages, the approach would be a bit different. In OOP Languages, we have to pass in a class that implements a specific interface for filtering.

Conclusion #

In this tutorial we learned how to remove null or empty values from an array using the filter method. We also discussed how the filter method works by creating our own filter function. The filter method can be used in any situation where we want to test the values inside of an array. I'll leave you with some examples below.


const arr = ['1', 2, , null, 4, 5, undefined, false];

//filter all boolean values
console.log(arr.filter(val => typeof val ==="boolean")) //[false]

//filter values greater than 3
console.log(arr.filter(val => val > 3)) //[4,5]

//filter values that are of type string
console.log(arr.filter(val => typeof val ==="string")) //["1"]
1234567891011

Thank you for reading reaching this far! If you like tutorials like these, please leave a like or subscribe to my newsletter below!

Credits: Image by Laurin Vontobel from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle