views:

109

answers:

5

Is there a function/method to retrieve the index of an item in an array from its value in JavaScript?

In other words I'm looking for the JavaScript equivalent for the Python .index() lists method:

>>> ['stackoverflow','serverfault','meta','superuser'].index('meta')
2

Does the wheel already exist or have I to reinvent it?

+1  A: 

You could do

var lookingFor = 'meta';

var arrayIndex;

for (var i=0;i<array.length;i++) {

    if (array[i] === lookingFor) {
        arrayIndex = i;
    };    

};

Here is how you could do it similar to your example. This is untested, but it should work.

Array.prototype.index = function(findWhat) {

    for (i=0;i>this.length;i++) {

        if (this[i] === findWhat) {
            return i;
        };    

    };


};
alex
A: 
Array.prototype.GetIndex = function ( value )
{
    for (var i=0; i < this.length; i++) 
    {
     if (this[i] == value) 
     {
      return i;
     }
    }
}

var newQArr = ['stackoverflow','serverfault','meta','superuser'];

alert ( newQArr.GetIndex ( 'meta' ) );

Hope this helps.

rahul
+1  A: 
Myra
Does that work with arrays or only strings?
alex
This is a javascript fix for arrays,works for every type of array
Myra
Not supported in IE, plus some other older browsers. You should use indexOf where it exists and a fallback such as one of the fucntions listed here.
Tim Down
I dont understand why my answer is given negative score ?
Myra
Your implementation looks more like `lastIndexOf`. IOW the semantics of `indexOf` require you to loop forwards, not backwards, in the array.
Crescent Fresh
+1 to crescentfresh comment, it should return the index of the first occurrence.
Andrea Ambu
A: 

This type of stuff is usually done with a dict, could you use that instead. I'm not sure how the rest of your code depends on this structure. Otherwise, you pretty much have to roll your own.

dharga
any specific reason for the down vote?
dharga
+3  A: 

You are looking for the "indexOf" method. It is available in Mozilla, but not IE. However, it is easy to add support for this to IE (presuming you are ok with the idea of changing the Array.prototype -- there are some reasons why you may not want to do this.)

Here is the official documentation.

Here is a reference implementation, taken from the above page:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Good luck!

Chris Nielsen