Determine if string is in list in JavaScript

Determine if string is in list in JavaScript

In SQL we can see if a string is in a list like so:
Column IN (‘a’, ‘b’, ‘c’)

What’s a good way to do this in JavaScript? It’s so clunky to do this:
if (expression1 || expression2 || str === ‘a’ || str === ‘b’ || str === ‘c’) {
// do something

And I’m not sure about the performance or clarity of this:
if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
// do something

Or one could use the switch function:
var str = ‘a’,
flag = false;

switch (str) {
case ‘a’:
case ‘b’:
case ‘c’:
flag = true;

if (expression1 || expression2 || flag) {
// do something

But that is a horrible mess. Any ideas?
In this case, I have to use Internet Explorer 7 as it’s for a corporate intranet page. So [‘a’, ‘b’, ‘c’].indexOf(str) !== -1 won’t work natively without some syntax sugar.


Solution 1:

You can call indexOf:

if (['a', 'b', 'c'].indexOf(str) >= 0) {
    //do something

Solution 2:

EcmaScript 6

If you’re using ES6, you can construct an array of the items, and use includes:

['a', 'b', 'c'].includes('b')

This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined. includes also works on JavaScript typed arrays such as Uint8Array.

Without An Array

You could add a new isInList property to strings as follows:

if (!String.prototype.isInList) {
   String.prototype.isInList = function() {
      let value = this.valueOf();
      for (let i = 0, l = arguments.length; i < l; i += 1) {
         if (arguments[i] === value) return true;
      return false;

Then use it like so:

'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false

You can do the same thing for Number.prototype.


If you are using a modern browser, indexOf always works. However, for IE8 and earlier you’ll need a polyfill.

Related:  How to trigger checkbox click event even if it's checked through javascript code?

If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can’t match a missing element to undefined as in the array [1, , 2].

Polyfill for indexOf in Internet Explorer 8 and earlier, or any other browser lacking it

You can always use a standards-compliant custom polyfill to make this work in older browsers.

In this situation where I had to make a solution for Internet Explorer 7, I “rolled my own” simpler version of the indexOf() function that is not standards-compliant:

if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(item) {
      var i = this.length;
      while (i--) {
         if (this[i] === item) return i;
      return -1;

However, I don’t think modifying Array.prototype is the best answer in the long term. Modifying Object and Array prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys:

Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
blah // Extra member iterated over!

Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn’t zealously guarding against inherited keys, everything can break.

Related:  Convert string in dot notation to get the object reference [duplicate]

The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x.

The new ES6 way to avoid this extra-key problem is to use of instead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you’ll probably just want to use includes as stated above.

Solution 3:

Most of the answers suggest the Array.prototype.indexOf method, the only problem is that it will not work on any IE version before IE9.

As an alternative I leave you two more options that will work on all browsers:

if (/Foo|Bar|Baz/.test(str)) {
  // ...

if (str.match("Foo|Bar|Baz")) {
  // ...

Solution 4:

Arrays have an indexOf method which can be used to search for strings:

js> a = ['foo', 'bar', 'baz']
js> a.indexOf('bar')
js> a.indexOf('quux')

Solution 5:

A trick I’ve used is

>>> ("something" in {"a string":"", "somthing":"", "another string":""})
>>> ("something" in {"a string":"", "something":"", "another string":""})

You could do something like

>>> a = ["a string", "something", "another string"];
>>> b = {};
>>> for(var i=0; i<a.length;i++){b[a[i]]="";} /* Transform the array in a dict */
>>> ("something" in b)

Solution 6:

Here’s mine:

    return (Array.apply(null, arguments).indexOf(this.toString()) != -1)

var x = 'abc';
if (x.inList('aaa','bbb','abc'))

This one is faster if you’re OK with passing an array:

    return (list.indexOf(this.toString()) != -1)

var x = 'abc';
if (x.inList(['aaa','bbb','abc']))

Here’s the jsperf:

Related:  console-like interface on a web page using javascript [closed]