Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements in an array using Lodash

I have this array:

var fruits = ['Apple', 'Banana', 'Orange', 'Celery']; 

And I use Lodash's remove like so:

_.remove(fruits, function (fruit) {   return fruit === 'Apple' || 'Banana' || 'Orange'; }) 

The result is ['Apple', 'Banana', 'Orange', 'Celery'], while I expected it to be ['Apple', 'Banana', 'Orange']. Why is this so?

like image 766
bard Avatar asked Jan 20 '15 02:01

bard


People also ask

How can I remove an element in array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove an object with Lodash?

The Lodash _. unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.

How do I remove an item from an array by value?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.


2 Answers

Because when fruit is "Celery", you are testing:

"Celery" === 'Apple' || 'Banana' || 'Orange' 

which evaluates to

false || true || true 

which is true.

You can't use that syntax. Either do it the long way around:

_.remove(fruits, function (fruit) {   return fruit === 'Apple' || fruit === 'Banana' || fruit === 'Orange' }); 

or test for array membership:

_.remove(fruits, function (fruit) {   return _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1 }); 

This is not limited to JavaScript, and is in fact a common mistake (e.g. this question)

like image 66
Amadan Avatar answered Oct 06 '22 08:10

Amadan


You can use the method _.pull from lodash 2.0 and up

var fruits = ['Apple', 'Banana', 'Orange', 'Celery'];    _.pull(fruits, 'Apple', 'Banana', 'Orange'); // ['Celery']    document.write(fruits);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>
like image 41
gustavogelf Avatar answered Oct 06 '22 07:10

gustavogelf