Find the index of an item in a Javascript array
Posted March 23rd, 2010 in Javascript
Javascript 1.6 introduced the Array.indexOf() function. Javascript 1.6 is available in Firefox from version 1.5 and current versions of Chrome, Safari and Opera; importantly, it is not in any versions of Internet Explorer at all (as at the time of this post).
Array.indexOf() function
Browsers that do not support indexOf() can easily have it added using the following function which extends the Array prototype.
I found the function in numerous sources on the Internet most of which attribute it to the Mozilla Foundation, but I could not find the ultimate source of the function. If anyone knows please let me know in the comments at the end of this post and I can link to the original source.
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
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;
};
}
Note the "if (!Array.prototype.indexOf)" line means that the prototype will only be added if it doesn't already exist. This means browsers which already have the function natively defined will use their own internal function instead of the one defined in the code above.
You can then do something like this:
var a = new Array("a", "b", "c", "d");
alert(a.indexOf("c"));
which would alert "2" in a dialog box.
Related posts:
- Remove an item from a Javascript array (Friday, March 19th 2010)
- Iterate through an associative array the jQuery way (Friday, January 29th 2010)
- Loop through key value pairs from an associative array with Javascript (Friday, April 3rd 2009)
- Assigning values to associative arrays in Javascript (Sunday, December 30th 2007)

Comments
blog comments powered by Disqus