Possible Duplicate:
Find object by id in an array of JavaScript objects
How to check if value exists in this JavaScript array?
For example:
var arr = [
{id: 1, color: 'blue'},
{id: 2, color: 'red'},
{id: 3, color: 'yellow'}
];
alert( indexOf('blue') ); // How can I get the index of blue??
Simply loop through the array and check the colour value:
for(var i = 0 ; i < arr.length -1 ; i++){
if(arr[i].color == 'red'){
alert(i);
}
}
And of course you could just wrap it in a helper function as follows:
function colourIndex(colour){
for(var i = 0 ; i < arr.length -1 ; i++){
if(arr[i].color == colour){
return i;
}
}
}
found_flag = false;
for (i = 0; i < arr.length; i++) {
if (arr[i].color == 'blue') {
found_flag = true;
break;
}
}
if (found_flag === true)
{
alert(i);
} else {
alert('not found');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With