tags:

views:

48

answers:

3

I know the name of the item and would like to know its position in the array, how would I do that?

+2  A: 
["a","b","c","d","e"].indexOf("c")
2
S.Mark
+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
+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
Shouldn't that be `if(!Array.prototype.indexOf){` ? I'm pretty sure `Array` (the constructor) never has an `indexOf` on it.
T.J. Crowder
Thanks for the link. I didn't know about that.
Frank Furd
@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
@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
@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
+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