10

Possible Duplicate:
array.contains(obj) in JavaScript

Let's say I have an array = [0,8,5]

What is the fastest way to know if 8 is inside this one.. for example:

if(array.contain(8)){
 // return true
}

I found this : Fastest way to check if a value exist in a list (Python)

and this : fastest way to detect if a value is in a set of values in Javascript

But this don't answer to my question. Thank you.

Community
  • 1
  • 1
Ydhem
  • 928
  • 2
  • 14
  • 36

4 Answers4

10

Use indexOf() to check whether value is exist or not

array.indexOf(8)

Sample Code,

var arr = [0,8,5];
alert(arr.indexOf(8))​; //returns key

Update

For IE support

//IE support
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

var arr = [0,8,5];
alert(arr.indexOf(8))
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
4

You can use a indexOf() function

var fruits = ["a1", "a2", "a3", "a4"];
var a = fruits.indexOf("a3");

The output will be: 2

Dineshkani
  • 2,899
  • 7
  • 31
  • 43
0

You can use indexOf or you can try this:

$.inArray(value, array)
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
-1

phpjs has a nice php's in_array function's port to javascript, you may use it

http://phpjs.org/functions/in_array/

see example:

in_array('van', ['Kevin', 'van', 'Zonneveld']);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Kemal Dağ
  • 2,743
  • 21
  • 27