Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Best way to find if a value is inside an object in an array [duplicate]

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??
like image 573
wilsonpage Avatar asked Oct 17 '11 11:10

wilsonpage


2 Answers

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; 
        }  
    }
}
like image 58
cillierscharl Avatar answered Oct 29 '22 21:10

cillierscharl


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');
}
like image 35
vzwick Avatar answered Oct 29 '22 21:10

vzwick