In this tutorial, we will look through how to remove null from an Array using Lodash or without Lodash. You may be wondering what lodash is.
Table of Contents
What is Lodash?
Lodash is a popular JavaScript based library which provides many functions for the web developers and the coders by providing them some helper functions like map, filter, invoke and also offers function binding, JavaScript templating, deep equality checks, creating indexes and much more.
To remove null from an Array we will use Lodash’s filter function. It primarily takes two parameters which are:
- Collection
- Predicate
Collection is basically the object or the array to iterate over. And predicate is the function which is used in each iteration. The filter() function returns a new array containing all elements predicate returned a truthy value for. To remove null, you can call filter() with v => v !== null as the predicate.
Removing null from an Array using Lodash
Code
const _ = require('lodash');
const dummyArr = ['dummy', true, null, undefined, 69];
_.filter(dummyArr, v => v !== null);
Output
['dummy', true, undefined, 69]
What does filter function do?
The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.
To remove null using filter function, you can use the _.isNull function as the predicate. Add a negate in front of the isNull and all null values will be filtered out. Let’s see an example:
Code
const _ = require('lodash');
const dummyArray = ['dummy', true, null, undefined, 69]; // ['dummy', true, undefined, 69]
_.filter(dummyArray, el => !_.isNull(el));
Removing null from an Array without Lodash
Even without using lodash we can filter out false elements in an array or an object. It is not too hard to make a vanilla js solution using Array forEach, and drop the use of lodash for this kind of task. We are basically looping over the elements of an array, and checking a condition on each element, if that condition is valid for the element then the element is pushed to a new array.
Code
var dummyArr = [null, 2, 'food', NaN, false, 'bar', undefined, undefined, 69];
var compact = function (a) {
var n = [];
a.forEach(function (el) {
if (!!el) {n.push(el)}
});
return n;
};
console.log( compact(dummyArr) ); // [ 2, 'food', 'bar', 69 ]
That’s it for this tutorial. Hope you have understood how to use lodash to remove null from an Array. In the next blog we will discuss how to use lodash to remove null from objects.
2 thoughts on “How to remove null from an Array w/wo Lodash?”