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?
-
1Check it out : stackoverflow.com/questions/237104/…Anthony Simmon– Anthony Simmon2012年09月27日 14:07:14 +00:00Commented Sep 27, 2012 at 14:07
-
1indexOf MDN Docsepascarello– epascarello2012年09月27日 14:07:38 +00:00Commented Sep 27, 2012 at 14:07
-
iterate through array and compare one by one!SachinGutte– SachinGutte2012年09月27日 14:07:43 +00:00Commented Sep 27, 2012 at 14:07
-
1How is this question not closed yet when it's a duplicate of a ton of other questions? Best way to find an item in a JavaScript array?, array.contains(obj) in JavaScript etc. Instead moderators close or delete actually useful questions.Dan Dascalescu– Dan Dascalescu2014年03月04日 23:39:53 +00:00Commented Mar 4, 2014 at 23:39
5 Answers 5
There is an indexOf method that all arrays have (except Internet Explorer 8 and below) 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 polyfill this method using the code in the MDN article.
3 Comments
includes func, which is exactly what author is asking for. Below is an example: ['A', 'B'].includes('A') // >> true ['A', 'B'].includes('C') // >> falseincludes() is better in 2020 and beyond. More info here 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
6 Comments
var stringArray = ["String1", "String2", "String3"];
return (stringArray.indexOf(searchStr) > -1)
Comments
Create this function prototype:
Array.prototype.contains = function ( needle ) {
for (var i in this) { // Loop through every item in array
if (this[i] == needle) return true; // return true if current item == needle
}
return false;
}
and then you can use following code to search in array x
if (x.contains('searchedString')) {
// do a
}
else
{
// do b
}
3 Comments
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() .