Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
possible duplicate of Javascript - array.contains(obj) – annakata Oct 1 '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 1 '10 at 13:09

3 Answers

up vote 3 down vote accepted

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

share|improve this answer
1  
this would work, I'm using jquery. thanks – bba Oct 1 '10 at 13:01
@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 1 '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 1 '10 at 13:03
Ill be sure to keep that in mind. thanks – bba Oct 1 '10 at 13:04

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.