Skip to content Skip to sidebar Skip to footer

How Can I Find Out The Position Of An Item Contained By An Array?

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

Solution 1:

["a","b","c","d","e"].indexOf("c")
2

Solution 2:

You could loop through the array:

vararray = ['item1', 'item2', 'item3'];
functionfindIndex(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:

vararray = ['item1', 'item2', 'item3'];
functionfindIndex(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' ;
});

Solution 3:

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;

Post a Comment for "How Can I Find Out The Position Of An Item Contained By An Array?"