Reputation: 9756
I have an array of string and want to instantly remove some of them. But it doesn't work
var list = ['a', 'b', 'c', 'd']
_.remove(list, 'b');
console.log(list); // 'b' still there
I guess it happened because _.remove
function accept string as second argument and considers that is property name. How to make lodash do an equality check in this case?
Upvotes: 19
Views: 18680
Reputation: 2300
One more option for you is to use _.pull, which unlike _.without, does not create a copy of the array, but only modifies it instead:
_.pull(list, 'b'); // ['a', 'c', 'd']
Reference: https://lodash.com/docs#pull
Upvotes: 29
Reputation: 7912
Function _.remove doesn't accept a string as second argument but a predicate function which is called for each value in the array. If the function returns true
the value is removed from the array.
Lodas doc: https://lodash.com/docs#remove
Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is bound to thisArg and invoked with three arguments: (value, index, array).
So, if you want to remove b
from your array you should something like this:
var list = ['a', 'b', 'c', 'd']
_.remove(list, function(v) { return v === 'b'; });
["a", "c", "d"]
Upvotes: 4
Reputation: 33399
As Giuseppe Pes points out, _.remove
is expecting a function. A more direct way to do what you want is to use _.without
instead, which does take elements to remove directly.
_.without(['a','b','c','d'], 'b'); //['a','c','d']
Upvotes: 7