Lodash remove from string array

I have an array of strings and you want to delete some of them immediately. But that does not work.

var list = ['a', 'b', 'c', 'd'] _.remove(list, 'b'); console.log(list); // 'b' still there 

I assume this happened because the _.remove function takes the string as the second argument and considers that this is the name of the property. How to make lodash do an equality check in this case?

+6
source share
3 answers

Another option for you is to use _.pull, which, unlike _.without, does not create a copy of the array, but only modifies it:

 _.pull(list, 'b'); // ['a', 'c', 'd'] 

Link: https://lodash.com/docs#pull

+13
source

As Giuseppe Pes points out, _.remove expects a function. A more direct way to do what you want is to use _.without instead to remove items directly.

 _.without(['a','b','c','d'], 'b'); //['a','c','d'] 
+2
source

The _.remove function does not take a string as the second argument, but a predicate function that 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 the array that the predicate returns the truth for and returns an array of deleted elements. The predicate is associated with thisArg and is called with three arguments: (value, index, array).

So, if you want to remove b from your array, you should do something like this:

 var list = ['a', 'b', 'c', 'd'] _.remove(list, function(v) { return v === 'b'; }); ["a", "c", "d"] 
+1
source

Source: https://habr.com/ru/post/988020/


All Articles