Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, Fastest way to know if a certain value is in a array? [duplicate]

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.

like image 970
Ydhem Avatar asked Nov 27 '12 15:11

Ydhem


1 Answers

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))
like image 93
Muthu Kumaran Avatar answered Sep 19 '22 21:09

Muthu Kumaran