Home » Blog » Remove Null Values From Array in JavaScript
Remove Null Values From Array in JavaScript

Remove Null Values From Array in JavaScript

Here’s how you can remove null values from an array in JavaScript. I will show you two methods, the first one with pure JavaScript and the array filter method and the second one with Lodash.

Remove Null Values from Array With Pure JavaScript

I recommend this method over the one with Lodash because you don’t have to use an external library. All you have to do is use the Array.prototype.filter() implemented in JavaScript. This built-in method creates a shallow copy of your array based on the filter condition you provide.

Here’s how it’s working:

const whatIsLife = ["Life", "is", null, "beautiful", null, "!"]

const thisIsLife = whatIsLife.filter(element => element !== null)

console.log(thisIsLife)
// Output: ["Life", "is", "beautiful", "!"]

As you can see above, our whatIsLife array contains null values. By using the filter method, we specify that we want to keep only elements that are different than null (yes, because life is beautiful!).

If you print the new thisIsLife array, you’ll have an array with non-null values.

Here’s a shortened version of the above example:

const whatIsLife = ["Life", "is", null, "beautiful", null, "!"]

// Returning `element` will only return values if they
// are non-null
const thisIsLife = whatIsLife.filter(element => element)

console.log(thisIsLife)
// Output: ["Life", "is", "beautiful", "!"]

With Lodash

Even if I recommend the first method, it’s always interesting to discover other ways of removing null values from an array. This time, let’s learn how to do it with Lodash, a JavaScript library.

You’ll notice the syntax will differ a little, but the function we’ll use is the same as the one built-in in JavaScript. Indeed, the Lodash function is called filter.

It’s time for an example!

import _ from "lodash"

const whatIsLife = ["Life", "is", null, "beautiful", null, "!"]

const thisIsLife = _.filter(whatIsLife, (element) => element !== null)

console.log(thisIsLife)
// Output: ["Life", "is", "beautiful", "!"]

Now you know how to remove null values in a JavaScript array, you can learn how to remove an element from an array.


Thanks for reading. Let’s connect!

➡️ I help you grow into Web Development, and I share my journey as a Nomad Software Engineer. Join me on Twitter for more. 🚀🎒

Gaël Thomas

🚀 Help you grow into Web Development 👨‍💻 Share about my journey as Nomad Software Engineer 🧰 Into JavaScript, TypeScript, Node, and React

Post navigation