Sometimes, we want to remove elements in an array using Lodash.
In this article, we’ll look at how to remove elements in an array using Lodash.
How to remove elements in an array using Lodash?
To remove elements in an array using Lodash, we can use remove
method.
For instance, we write:
const fruits = ['Apple', 'Banana', 'Orange', 'Grape']
_.remove(fruits, (fruit) => {
return _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1
});
console.log(fruits)
We call remove
with fruits
and a callback that returns the condition for the items that should be removed.
We returned _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1
so 'Apple'
, 'Banana'
and 'Orange'
are removed from fruits
.
The removed items are returned.
As a result, fruits
is ['Grape']
after remove
is called.
Conclusion
To remove elements in an array using Lodash, we can use remove
method.