1

I am returned a string, fruit which could have many values, for example: banana, apple, grapes, orange, mango etc.

I want to output the value of this string, but I only want to display some of them. This has made my IF statement long & ugly:

 if ( fruit != 'apple' || fruit != 'grapes' || fruit != 'banana' ) {
      // display them
 }

How else could I write this? Would .filter work? Can I put the unwanted fruits into an array and say if fruit matches an array value, do nothing?

izolate
  • 1,590
  • 4
  • 22
  • 35
  • 2
    Asking JS to do `fruit != 'apple' || fruit != 'grapes'` would mean that the first condition is TRUE if `fruit == 'grapes'` and also TRUE if `fruit == 'apple'` for the second condition. Your statement has virtually no effect. – Brian Jul 24 '13 at 14:37
  • Good point. What's the correct way to lay it out? – izolate Jul 24 '13 at 14:43
  • 2
    @izolate That method requires `&&` instead of `||`, but the tidiest way of checking against multiple values is in my answer below – MDEV Jul 24 '13 at 14:45
  • The correct would be using && between the elements since you want to display when it not apple AND not grapes etc. Like it is now it will display for grapes since it isn't apple and OR is satisfied with one being true. – Sylwester Jul 24 '13 at 14:49
  • 2
    This is asked once a week, searching a bit doesn't hurt. – Fabrício Matté Jul 24 '13 at 14:51
  • And [Reduce multiple ORs in IF statement in Javascript](http://stackoverflow.com/q/2630364/1331430) – Fabrício Matté Jul 24 '13 at 14:53
  • And [IF Statement Multiple Answers - Same Result Javascript](http://stackoverflow.com/q/8711174/1331430) and a hundred more. All you have to do is flip the result. – Fabrício Matté Jul 24 '13 at 14:56

2 Answers2

7
var dontMatch = new Array('apple','grapes','banana');
if(dontMatch.indexOf(fruit) == -1)
{
    //fruit is none of the above
}
MDEV
  • 10,730
  • 2
  • 33
  • 49
  • 2
    Array literals are preferred. – SLaks Jul 24 '13 at 14:38
  • 1
    It should be noted that the `indexOf` method for arrays is a fairly new feature in JS, so if you have to support old IE, et al., you should have a workaround as well. The following page outlines a good workaround: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – HartleySan Jul 24 '13 at 14:38
  • @SLaks Yea, I'd just changed my answer when I noticed your comment lol – MDEV Jul 24 '13 at 14:38
  • Painless and succinct. Thanks! – izolate Jul 24 '13 at 14:45
  • @izolate Glad to have helped. Please remember to help future visitors of this question by marking the answer as accepted – MDEV Jul 24 '13 at 14:51
1

Perhaps try a case statement?

switch(fruit) {
    case 'apple': // dont display
        break;
    case 'grapes': // dont display
        break;
    case 'banana': // dont display
        break;
    case 'orange': // display
        break;
    case 'mango': // display
        break;
}
Tro
  • 897
  • 9
  • 32