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. ππ
Top comments (0)