7

I have a long list of strings to compare against the same variable.

Is there a shorter way to do this?

if(val=="kivi" || val=="apples" || val=="lychee" || val=="banana.C" || val=="mangos")
Chris
  • 57,622
  • 19
  • 111
  • 137
Becky
  • 5,467
  • 9
  • 40
  • 73

5 Answers5

12

Use indexOf with array of values

var valArr = ["kivi","apples","lychee","banana.C","mangos"];

if(valArr.indexOf(val) > -1){
   .......
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
5

You can create an array and check if the value exists in array.

Array#includes

var fruits = ['kivi', 'apples', 'lychee', 'banana.C', 'mangos'];

if (fruits.includes(val)) {

var fruits = ['kivi', 'apples', 'lychee', 'banana.C', 'mangos'];

document.getElementById('test').addEventListener('keyup', function() {
    document.getElementById('result').textContent = 'Contains? ' + fruits.includes(this.value);
}, false);
<input type="text" id="test" />
<div id="result"></div>

Note that this is supported in latest browsers. However, polyfill can be used in older browsers.

Browser CompatibilityMDN

Tushar
  • 85,780
  • 21
  • 159
  • 179
3

Nope. That's about as short as it gets for direct string comparison.

If you have a lot of values to compare against you could put those values in an array and use indexOf, like this:

var comparisons = ["kivi", "apples", "lychee", "banana.C", "mangos" ];
if (comparisons.indexOf(val) != -1) {
    // do something...
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

One line check:

if (['kivi', 'apples', 'lychee', 'banana.C', 'mangos'].includes(val)) {
    // Some code
}
Skules
  • 21
  • 2
  • When you answered a question with code snippet, please try to explain it. You can visit and check [how to answer a question](https://stackoverflow.com/help/how-to-answer). – Yunus Temurlenk Apr 15 '20 at 06:46
1
myArr = ["kivi", "apples", "lychee", "banana.C", "mangos"];

if(myArr.indexOf(val) != -1)
{  
   // Element Found!!
}
Jenson M John
  • 5,499
  • 5
  • 30
  • 46