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?
5 Answers 5
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!
Comments
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;
};
};
};
Comments
Your function is indexOf
var array = new Array();
array[0] = "A";
array[1] = "B";
array[2] = "C";
array[3] = "D";
var index = array.indexOf("A");
Edit: This is a javascript fix for indexing
[].indexOf || (Array.prototype.indexOf = function(v){ for(var i = this.length; i-- && this[i] !== v;); return i; });
5 Comments
lastIndexOf
. IOW the semantics of indexOf
require you to loop forwards, not backwards, in the array.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.
Comments
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.