简体   繁体   中英

Lodash remove from string array

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM