Open In App

How to Remove Null from an Array in Lodash ?

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Run the below command to install Lodash:

npm i lodash

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.

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

JavaScript
const _ = require('lodash');
let arr = [1, null, 3, null, 5];
let res = _.compact(arr);
console.log(res);

Output:

[ 1, 3, 5 ]

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.

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 ]

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.

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

JavaScript
const _ = require('lodash');
let arr = [null, null, 3, null, 5];
let res = _.reject(arr, _.isNull);
console.log(res);

Output:

[ 3, 5 ]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads