297

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?

4

5 Answers 5

516

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
  • 2
    Is there a better way to do this is React, Babel ES2017?
    – devssh
    CommentedAug 27, 2018 at 7:39
  • 15
    this approach works, but looks a bit as misuse. I would rather recommend to use includes func, which is exactly what author is asking for. Below is an example: ['A', 'B'].includes('A') // >> true ['A', 'B'].includes('C') // >> falseCommentedJun 18, 2019 at 5:53
  • 3
    @StanislauBaranouski - Indeed! includes() is better in 2020 and beyond. More info here
    – rinogo
    CommentedNov 24, 2020 at 1:25
69

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
  • Good answer, but it's worth mentioning compatibility concerns for old IE versions when using indexOf.
    – Gaʀʀʏ
    CommentedDec 18, 2015 at 22:35
  • 52
    no one cares about ie, even microsoft :DCommentedNov 17, 2016 at 19:06
  • 4
    @andygoestohollywood Sadly some companies still use IE. Just because some companies are in the stone age does not mean you should dump 9% of your market.CommentedJan 8, 2018 at 23:18
  • 5
    @AlexFallenstedt Yeah, no. Internet Explorer is a proven security threat that is incompatible with modern web technologies. If a company can afford to spend $X to use your web app, they can afford to spend $0 to install Firefox or something else that isn't riddled with backdoors. If they won't do it for some stupid reason, add $Y to the sticker price and package your app in NW.js or Electron.CommentedJun 9, 2018 at 4:16
  • 2
    @SkylarIttner Many multinational companies use IE for their Intranet. Why? Back in the day an in-house development team decided to make the intranet work on one browser. The company I work for is like this. They chose IE. Today this world wide company that has 216K employees and counting. Enterprise legacy systems are so interconnected it really would require a huge amount of time and money to make any changes. For some organizations it nigh on impossible to commit to this just so its workers can stop whinging about IE. To them there is no business value in it, and there never will be.CommentedJun 10, 2018 at 5:07
43
var stringArray = ["String1", "String2", "String3"]; return (stringArray.indexOf(searchStr) > -1) 
    10

    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
    5

    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().

    2
    • 3
      And you reinvented indexOf supported by modern day browsers.CommentedSep 27, 2012 at 14:08
    • 9
      ...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
      CommentedSep 27, 2012 at 15:16

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.