Open In App

How to Remove an Element from a list in Lodash?

Last Updated : 26 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To remove an element from a list, we employ Lodash functions such as without, pull, or reject. These methods enable us to filter out elements from the list based on specific conditions, effectively excluding those that match the criteria.

Below are the approaches to remove an element from a list in lodash:

Using Lodash _.without() Method

In this approach, we use the _.without method from Lodash with the original list and the element ‘banana’ as arguments, which returns a new array excluding ‘banana’.

Command to install lodash:

npm i lodash

Example: The below example uses without function to remove an element from a list in lodash.

JavaScript
const _ = require('lodash');
let list = ['apple', 'banana', 'cherry', 'orange'];
let res = _.without(list, 'banana');
console.log(res); 

Output:

[ 'apple', 'cherry', 'orange' ]

Using Lodash _.pull() Method

In this approach, we are using the _.pull method from Lodash directly on the list, removing the element ‘css’ and modifying the list in place, resulting in the updated list without ‘css’.

Command to install lodash:

npm i lodash

Example: The below example uses the pull function to remove an element from a list in lodash.

JavaScript
const _ = require('lodash');
let list = ['html', 'css', 'javascript', 'python'];
_.pull(list, 'css');
console.log(list);

Output:

[ 'html', 'javascript', 'python' ]

Using Lodash _.reject() Method

In this approach, we are using the _.reject method from Lodash with a predicate that checks for equality with ‘banana’, creating a new array excluding ‘banana’ and keeping other elements in the list.

Command to install lodash:

npm i lodash

Example: The below example uses the reject function to remove an element from a list in lodash.

JavaScript
const _ = require('lodash');
let list = ['apple', 'banana', 'cherry', 'orange'];
let res = _.reject(list, item => item === 'banana');
console.log(res); 

Output:

[ 'apple', 'cherry', 'orange' ]

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

Similar Reads