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?
views:
64answers:
3
+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
2010-05-10 12:18:59
Wouldn't that be lastIndexOf?
Matthew Flaschen
2010-05-10 12:22:31
Fixed; thanks.
SLaks
2010-05-10 12:23:56
Here is the FF implementation of indexOf method https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf#Compatibility
Amarghosh
2010-05-10 12:30:19
@SLaks, your `indexOf` implementation is lacking. Have a look at the one linked to by Amarghosh.
J-P
2010-05-10 13:38:31
Fixed again; thanks
SLaks
2010-05-10 14:23:50
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
2010-05-10 12:19:25
A:
Consider Objx for working with Arrays http://code.google.com/p/objx/wiki/Plugins
Mat Ryer
2010-05-10 12:24:29