Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  69] [ 2]  / answers: 1 / hits: 87220  / 10 Years ago, tue, january 20, 2015, 12:00:00

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?


More From » lodash

 Answers
35

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)


[#68161] Friday, January 16, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighm

Total Points: 423
Total Questions: 101
Total Answers: 112

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;