I know the name of the item and would like to know its position in the array, how would I do that?
+1 Note to OP: Be aware that not all implementations have this yet; see Mark Byers' answer for what to do if it isn't there.
T.J. Crowder
2010-02-07 15:14:00
+1
A:
Use the indexOf method of Array. If it's not there add it (code example here or other places).
If you want to find a value by its name property, do this:
for (var i = 0; i < this.length; i++) {
if(this[i].name == name) {
return i;
}
}
return -1;
Mark Byers
2010-02-07 15:02:58
Shouldn't that be `if(!Array.prototype.indexOf){` ? I'm pretty sure `Array` (the constructor) never has an `indexOf` on it.
T.J. Crowder
2010-02-07 15:14:35
@T.J. Crowder: In the Mozilla implementation, I'm not sure why the constructor has the prototype members... `Array.hasOwnProperty('indexOf') == true;` ... pretty weird don't you think?
CMS
2010-02-07 15:26:26
@CMS: Yes indeed. The docs don't mention that. I'd still check the prototype. :-) (And just verified; Firefox has it on both.)
T.J. Crowder
2010-02-07 15:34:02
@T.J. Crowder: Yes, I also couldn't find *any* documentation, seems like a *"Mozilla Extension"*, I'm not sure why they did it...
CMS
2010-02-07 15:40:43
+1
A:
You could loop through the array:
var array = ['item1', 'item2', 'item3'];
function findIndex(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
}
alert(findIndex(array, 'item2'));
Or using a comparer function for more complex types:
var array = ['item1', 'item2', 'item3'];
function findIndex(array, comparer) {
for (var i = 0; i < array.length; i++) {
if (comparer(array[i])) {
return i;
}
}
return -1;
}
var index = findIndex(array, function(item) {
return item === 'item2' ;
});
Darin Dimitrov
2010-02-07 15:03:12