-1

I'm working on a game and I have a variable id. I need to compare that to multiple integers (lets say 10). I know you can simply use the || and do

if (id == 1 || id == 2 || id == 3) 

which is perfectly fine, except in this case, I need to do that 10-15 times. Is there any quicker way to do this (it's the same variable that I'm comparing. Just different numbers).

I don't want an answer requiring a switch statement (which is also almost as much work). And I also don't want an answer using the || operator (like I showed in the code above).

Aniket G
  • 3,471
  • 1
  • 13
  • 39
  • Anoter duplicate: [How do I check if an array includes an object in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript?rq=1) – Pinke Helga Mar 07 '19 at 01:01

3 Answers3

1

Put the numbers that you want to check against in an array and check if the id exists in it using indexOf :

const id = 2;
const arr = [1,2,3];

if (arr.indexOf(id) > -1) 
  console.log('it exists');
Taki
  • 17,320
  • 4
  • 26
  • 47
1

You can use an Array to hold all the values you are comparing id against and use Array#indexOf to check if id is inside the Array.

var values = [1, 2, 3];
if(values.indexOf(id)!==-1){
  //id equals one of the elements of the values array
}

If you need to know which element id is equal to, you can store the index that it was found in the array as and then get the element of the Array at that index.

var values = [1, 2, 3];
var index = values.indexOf(id);
if(index!==-1){
  var value = values[index];//this is the value of id
  //id equals one of the elements of the values array
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can use an array and then validate that id using the function includes.

const id = 2;
const array = [1, 2, 3];

if (array.includes(id)) console.log("I'm in!");
Ele
  • 33,468
  • 7
  • 37
  • 75
  • This answer is lost here. It should be added to the popular duplicates instead. It was already given in https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values but not in https://stackoverflow.com/questions/9121395/javascript-the-prettiest-way-to-compare-one-value-against-multiple-values – Pinke Helga Mar 07 '19 at 00:49