3

Is there a function in javascript to do this - test if a given value (a string in my case) exists in an array (of strings)? I know I could just loop over each value, but I'm wondering if js has a shorthand for this.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
bba
  • 14,621
  • 11
  • 29
  • 26
  • possible duplicate of [Javascript - array.contains(obj)](http://stackoverflow.com/questions/237104/javascript-array-containsobj) – annakata Oct 01 '10 at 13:07
  • Indexed arrays may not be the correct data structure if you need to do this frequently. Consider using an associative array / object representation (which affords you the logical `in` operator). – annakata Oct 01 '10 at 13:09

3 Answers3

3

jquery has .inArray() method. It's the best I know..

naugtur
  • 16,827
  • 5
  • 70
  • 113
  • @bba, you might want to add information like that to your question. And to the **tags** for your question. (Edited your question to add the 'jquery' tag.) – David Thomas Oct 01 '10 at 13:03
  • @bba - Be sure to tag your question with jQuery if that's the case, it will get very different answers in many cases. :) – Nick Craver Oct 01 '10 at 13:03
2

There's .indexOf() for this, but IE<9 doesn't support it:

if(array.indexOf("mystring") > -1) {
  //found
}

From the same MDC documentation page, here's what to include (before using) to make IE work as well:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

.indexOf() returns the index in the array the string was found at, or -1 if it wasn't found.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
0

For functions that are in php and should be in javascript or I haven't found yet I go to: http://phpjs.org

The function you want use if you're just using javascript is in_array here: http://phpjs.org/functions/in_array:432

Otherwise, use the jQuery solution on this page.

BenWells
  • 317
  • 1
  • 10