Home / Javascript / Find the index of an item in a Javascript array

Find the index of an item in a Javascript array

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 whichattribute it to the Mozilla Foundation, but I could not find theultimate source of the function. If anyone knows please let me know inthe comments at the end of this post and I can link to the originalsource.

//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.