Skip to content Skip to sidebar Skip to footer

Function To Get Index From An Array Of Objects Having Certain Value Of Provided Property

My question is based on and similar to this one but a little bit different because property name will be variable. How do I create a function which will return me index of object h

Solution 1:

functionindexOf(propertyName,lookingForValue,array) {
    for (var i in array) {
        if (array[i][propertyName] == lookingForValue) {
            return i;
        }
    }
    return undefined;
}

Edit: Please note that I do the loose type check '==' on purpose since you are giving an integer to this function whereas in the array the value you search for is a string.

Solution 2:

I make a function which can be helpful to you. Check it.

functionGetindexOf(propertyName,lookingForValue,array){
var obj = array;
for(o in obj)
{
   if(obj[o][propertyName] == lookingForValue)
   {
       //return index;
       alert("You have request for "+o+" index");
   }
 }
}

Post a Comment for "Function To Get Index From An Array Of Objects Having Certain Value Of Provided Property"