1

I use jQuery for my application and I have an array which contains string items:

var array = ["item","item1","item2","item3"]

How I can test if array contains "item"?

Christian Groleau
  • 813
  • 1
  • 12
  • 17
Valeriane
  • 936
  • 3
  • 16
  • 37

3 Answers3

5

You can use array.indexOf("item") - It returns -1 if the item is not found or the index where the item is found.

Note that this is not supported in older versions of IE.

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • Note that this uses `===` for comparison. MDN has a polyfill for those versions of IE here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf – JeffS Feb 20 '13 at 15:09
  • But better to use `$.inArray` - it will use hative `Array.indexOf` if available. – dfsq Feb 20 '13 at 15:11
  • @dfsq - Yes, better to use `$.inArray` as it'll work equally well on all browsers. – techfoobar Feb 20 '13 at 15:12
4
if ($.inArray("item", array) > -1)
1

Javascript

Modern browsers have Array#indexOf, which does exactly that; this is in the ECMAScript v5 edition specification, but it has been in several browsers for years. Older browsers can be supported using the code listed in the "compatibility" section at the bottom of that page.

if(array.indexOf("item") > -1){
    //doSomething
}

jQuery

jQuery has a utility function for this:

if($.inArray(value, array)){
    //doSomething
}

It returns the index of a value in an array. It returns -1 if the array does not contain the value.

Duplicated?

Community
  • 1
  • 1
Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85