284

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gtludwig
  • 5,411
  • 10
  • 64
  • 90
  • 1
    Check it out : http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – Anthony Simmon Sep 27 '12 at 14:07
  • 1
    indexOf [MDN Docs](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf) – epascarello Sep 27 '12 at 14:07
  • iterate through array and compare one by one! – SachinGutte Sep 27 '12 at 14:07
  • 1
    How 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?](http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array), [array.contains(obj) in JavaScript](http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) etc. Instead moderators [close or delete actually useful questions](https://pinboard.in/u:dandv/b:6e91b9606eb8). – Dan Dascalescu Mar 04 '14 at 23:39

5 Answers5

502

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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 2
    Is there a better way to do this is React, Babel ES2017? – devssh Aug 27 '18 at 07:39
  • 12
    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') // >> false – Stanislau Baranouski Jun 18 '19 at 05:53
  • 2
    @StanislauBaranouski - Indeed! `includes()` is better in 2020 and beyond. [More info here](https://stackoverflow.com/a/1473742/114558) – rinogo Nov 24 '20 at 01:25
66

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

fableal
  • 1,577
  • 10
  • 24
  • Good answer, but it's worth mentioning compatibility concerns for old IE versions when using indexOf. – Gaʀʀʏ Dec 18 '15 at 22:35
  • 51
    no one cares about ie, even microsoft :D – andygoestohollywood Nov 17 '16 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. – Alex Fallenstedt Jan 08 '18 at 23:18
  • @AlexFallenstedt depends on who your market is :) – brandito Feb 22 '18 at 03:05
  • 3
    @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. – Skylar Ittner Jun 09 '18 at 04: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. – Alex Fallenstedt Jun 10 '18 at 05:07
39
var stringArray = ["String1", "String2", "String3"];

return (stringArray.indexOf(searchStr) > -1)
FixMaker
  • 3,759
  • 3
  • 26
  • 44
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
}
kmoser
  • 8,780
  • 3
  • 24
  • 40
eridanix
  • 818
  • 1
  • 8
  • 27
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().

Community
  • 1
  • 1
ollie
  • 799
  • 2
  • 10
  • 24
  • 3
    And you reinvented indexOf supported by modern day browsers. – epascarello Sep 27 '12 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 Sep 27 '12 at 15:16