Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
just-boris Avatar asked May 27 '15 15:05

just-boris


People also ask

What is Lodash remove?

remove() method in Lodash removes all the elements from an array that returns a truthy value for the specified predicate. This method will mutate the original array and return an array of all the removed elements.

How do you clear an array in Lodash?

remove() Method. The _. remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.


2 Answers

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

like image 77
trevor Avatar answered Sep 28 '22 07:09

trevor


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']
like image 40
Retsam Avatar answered Sep 28 '22 08:09

Retsam