tags:

views:

64

answers:

3

Given a javascript array and one of its members, how to retrieve the member index without having to compare the contents of the member against every other member in the array?

+3  A: 

You need to call indexOf, like this:

var index = someArray.indexOf(value);

Since IE doesn't have indexOf, you'll need to make it yourself:

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;
    };
}
SLaks
Wouldn't that be lastIndexOf?
Matthew Flaschen
Fixed;​ thanks.
SLaks
Here is the FF implementation of indexOf method https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf#Compatibility
Amarghosh
@SLaks, your `indexOf` implementation is lacking. Have a look at the one linked to by Amarghosh.
J-P
Fixed again; thanks
SLaks
A: 
var array = ['a', 'b', 'c'];
// The following line returns the zero-based index of 'c'
array.indexOf('c'); // 2
// If the element is not found in the array, -1 is returned:
array.indexOf('z'); // -1

Sadly, Array#indexOf is not natively supported in Internet Explorer. See SLaks’s answer for a working fallback!

Mathias Bynens
Not supported in IE
Matt
A: 

Consider Objx for working with Arrays http://code.google.com/p/objx/wiki/Plugins

Mat Ryer