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?
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.
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.
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.
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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With