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

I have a string array and one string. I'd like to test this string against the array values and apply a condition the result - if the array contains the string do "A", else do "B".

How can I do that?

share|improve this question
1  
Check it out : stackoverflow.com/questions/237104/… – AsKaiser Sep 27 '12 at 14:07
indexOf MDN Docs – epascarello Sep 27 '12 at 14:07
iterate through array and compare one by one! – SachinG Sep 27 '12 at 14:07
possible duplicate of JavaScript equivalent of PHP's in_array() – Peter Mortensen Apr 8 at 14:37

5 Answers

There is an indexOf method that all arrays have (except in old version of Internet Explorer) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can use polyfill this method using the code in the MDN article.

share|improve this answer

You can use the indexOfmethod and "extend" the Array class with the method contains like this:

Array.prototype.contains = function(element){
    return this.indexOf(element) > -1;
};

with the following results:

["A", "B", "C"].contains("A") equals true

["A", "B", "C"].contains("D") equals false

share|improve this answer
var stringArray = ["String1", "String2", "String3"];

return (stringArray.indexOf(searchStr) > -1)
share|improve this answer
Create this function prototype:
    Array.prototype.contains = function ( needle ) {
       for (i in this) {
           if (this[i] == needle) return true;
       }
       return false;
    }

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}
share|improve this answer

This will do it for you:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle)
            return true;
    }
    return false;
}

I found it in Stack Overflow question JavaScript equivalent of PHP's in_array().

share|improve this answer
And you reinvented indexOf supported by modern day browsers. – epascarello Sep 27 '12 at 14:08
1  
...which isn't supported by IE before IE9 - a lot of people, myself included, have to develop for IE8 (and sadly IE7 too most of the time). Admittedly, the prototype method creating the indexOf function is a preferable solution to what I posted – ollie Sep 27 '12 at 15:16
I was not the -1, but you can extend those browsers like MDN indexOf](developer.mozilla.org/en-US/docs/JavaScript/Reference/…) suggests. – epascarello Sep 27 '12 at 15:42

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.