bard bard - 2 months ago 30
Javascript Question

Removing elements in an array using Lodash

I have this array:

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

And I use Lodash's
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?


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)