19

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?

3 Answers 3

29

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

Sign up to request clarification or add additional context in comments.

Comments

7

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']

Comments

4

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"]

7 Comments

The return value should be v == 'b', not v !== 'b'
@trevor no. That would match only b. We want the opposite
I think they just wanted to remove 'b' based on the comment in their code: 'b still there'
Yes, I want to remove 'b' from my list. So here should be equal expression
Also, I found that _.without does exactly what I need, but create a copy of array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.