Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IN clause using JavaScript code

I have JavaScript code in my app that checks values using the OR(||) condition as in code snippet below. The number of OR conditions is not small in most of my code.

Question: Is there a way to make the code that has many multiple OR conditions more concise by using something like this:value IN ('s','b','g','p','z')? I was interested in something that comes as close as possible to an IN clause.

if(value === "s" || value === "b" || value === "g" || value === "p" || value === "z") {

  //do something

 }
like image 940
Sunil Avatar asked Aug 13 '15 18:08

Sunil


2 Answers

The simplest way is to create an array of valid values, then make sure your value is in that list. You can use the indexOf method for that:

var allowed = ['s', 'b', 'g', 'p', 'z'];
if (allowed.indexOf(value) !== -1) {
  // do something
}

The ES6 standard introduces Sets, which has a has method to do a similar thing on unique values.

This will work for strings, numbers, and other simple non-object values. Comparing objects with === will only succeed if the array/set already contains the exact same object.

like image 116
ssube Avatar answered Sep 22 '22 02:09

ssube


You could do something like this:

var values = ['s','b','g','p','z'];

if (values.indexOf(value) > -1)
like image 36
Kevin Boucher Avatar answered Sep 21 '22 02:09

Kevin Boucher