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
  • 908
  • 2
  • 14
  • 34

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,301
  • 5
  • 46
  • 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,715
  • 7
  • 29
  • 43
0

You can use indexOf or you can try this:

$.inArray(value, array)
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
0

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
  • 214,658
  • 40
  • 293
  • 332
Kemal Dağ
  • 2,715
  • 20
  • 26