How to use filter Function In Lodash

In this approach, we are using the filter function from Lodash with a predicate that filters out null values, creating a new array res with elements that are not null from the array arr.

Example: The below example uses a filter function to Remove null from an Array in Lodash.

JavaScript
const _ = require('lodash');
let arr = [null, 2, null, 4, null];
let res = _.filter(arr, item => item !== null);
console.log(res);

Output:

[ 2, 4 ]

How to Remove Null from an Array in Lodash ?

Removing null values from Array is important because it improves data cleanliness and ensures accurate processing.

Below are the approaches to Remove null from an Array in Lodash:

Table of Content

  • Using compact Function
  • Using filter Function
  • Using reject Function

Run the below command to install Lodash:

npm i lodash

Similar Reads

Using compact Function

In this approach, we are using the compact function from Lodash to remove null values from the array arr, resulting in a new array res containing only non-null elements....

Using filter Function

In this approach, we are using the filter function from Lodash with a predicate that filters out null values, creating a new array res with elements that are not null from the array arr....

Using reject Function

In this approach, we are using the reject function from Lodash with the _.isNull predicate to exclude null values from the array arr, resulting in a new array res containing only non-null elements....

Contact Us