[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;
   default:
}

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.

This question is related to javascript string list

The answer is


I'm surprised no one had mentioned a simple function that takes a string and a list.

function in_list(needle, hay)
{
    var i, len;

    for (i = 0, len = hay.length; i < len; i++)
    {
        if (hay[i] == needle) { return true; }
    }

    return false;
}

var alist = ["test"];

console.log(in_list("test", alist));

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

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

Looks like you need to use in_array function.

jQuery -> inArray

Prototype -> Array.indexOf

Or, see these examples if you are not using jQuery or Prototype:

Stylistic note: variables named thisthing thatthing, should be named to tell you something about what they contain (noun).


RegExp is universal, but I understand that you're working with arrays. So, check out this approach. I use to use it, and it's very effective and blazing fast!

var str = 'some string with a';
var list = ['a', 'b', 'c'];
var rx = new RegExp(list.join('|'));

rx.test(str);

You can also apply some modifications, i.e.:

One-liner

new RegExp(list.join('|')).test(str);

Case insensitive

var rx = new RegExp(list.join('|').concat('/i'));


And many others!


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")) {
  // ...
}

A simplified version of SLaks' answer also works:

if ('abcdefghij'.indexOf(str) >= 0) {
    // Do something
}

....since strings are sort of arrays themselves. :)

If needed, implement the indexof function for Internet Explorer as described before me.


Thanks for the question, and the solution using the Array.indexOf method.

I used the code from this solution to create a inList() function that would, IMO, make the writing simpler and the reading clearer:

function inList(psString, psList) 
{
    var laList = psList.split(',');

    var i = laList.length;
    while (i--) {
        if (laList[i] === psString) return true;
    }
    return false;
}

USAGE:

if (inList('Houston', 'LA,New York,Houston') {
  // THEN do something when your string is in the list
}

My solution results in a syntax like this:

// Checking to see if var 'column' is in array ['a', 'b', 'c']

if (column.isAmong(['a', 'b', 'c']) {
  // Do something
}

And I implement this by extending the basic Object prototype, like this:

Object.prototype.isAmong = function (MyArray){
   for (var a=0; a<MyArray.length; a++) {
      if (this === MyArray[a]) { 
          return true;
      }
   }
   return false;
}

We might alternatively name the method isInArray (but probably not inArray) or simply isIn.

Advantages: Simple, straightforward, and self-documenting.


Here's mine:

String.prototype.inList=function(list){
    return (Array.apply(null, arguments).indexOf(this.toString()) != -1)
}

var x = 'abc';
if (x.inList('aaa','bbb','abc'))
    console.log('yes');
else
    console.log('no');

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

String.prototype.inList=function(list){
    return (list.indexOf(this.toString()) != -1)
}

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

Here's the jsperf: http://jsperf.com/bmcgin-inlsit


In addition to indexOf (which other posters have suggested), using prototype's Enumerable.include() can make this more neat and concise:

var list = ['a', 'b', 'c'];
if (list.include(str)) {
  // do stuff
}

Using indexOf(it doesn’t work with IE8).

if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
    // found
}

To support IE8, you could implement Mozilla’s indexOf.

if (!Array.prototype.indexOf) {
    // indexOf polyfill code here
}

Regular Expressions via String.prototype.match (docs).

if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {

}

You can call indexOf:

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

A trick I've used is

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

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)
true

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>