Get index of array of objects via jquery

FLuttenb picture FLuttenb · Oct 1, 2013 · Viewed 19.5k times · Source

I have the following array:

var = array[
            {"id" : "aa", "description" : "some description"},
            {"id" : "bb", "description" : "some more description"},
            {"id" : "cc", "description" : "a lot of description"}]

and I try to find the index of the array that contains the id === "bb". The solution I came up with is the following:

var i = 0;
while(array[i].id != "bb"){
   i++;
}
alert(i) //returns 1

Is there an easier way that has cross-browser functionality? I tried $.inArray(id,array) but it doesn't work.

Answer

musefan picture musefan · Oct 1, 2013

I don't see any problem with the complexity of your code, but I would recommend a couple of changes including adding some validation in case the value does not exists. Further more you can wrap it all in a reusable helper function...

function getArrayIndexForKey(arr, key, val){
    for(var i = 0; i < arr.length; i++){
        if(arr[i][key] == val)
            return i;
    }
    return -1;
}

This can then be used in your example like so:

var index = getArrayIndexForKey(array, "id", "bb");
//index will be -1 if the "bb" is not found

Here is a working example

NOTE: This should be cross browser compatible, and will also likely be faster than any JQuery alternative.