5

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??
Community
  • 1
  • 1
wilsonpage
  • 17,341
  • 23
  • 103
  • 147
  • 1
    Possible Duplicates: http://stackoverflow.com/questions/7740241/how-to-check-if-value-exists-in-this-javascript-array, http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects – Riz Oct 17 '11 at 11:32
  • Is it JSON and would you want to get ID? – sll Oct 17 '11 at 11:37
  • @sll: Does not look like JSON. – Felix Kling Oct 17 '11 at 11:55

5 Answers5

5

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; 
        }  
    }
}
cillierscharl
  • 7,043
  • 3
  • 29
  • 47
3
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');
}
vzwick
  • 11,008
  • 5
  • 43
  • 63
3

You have to iterate over the array, searching for the blue object. If you got it you have your index.

var index = 0;
for(; index<arr.length; index++) {
    if(arr[index].color == 'blue') {
        break;
    }
}
alert(index)
styrr
  • 829
  • 4
  • 9
2

You might want to create a more general solution instead of duplicating code all over the place

Array.prototype.indexOf = (function() {
    var old = Array.prototype.indexOf ||
        function(v) {
            var i, l = this.length;
            for (i = 0; i < l; ++i) {
                if (this[i] === v) {
                    return i;
                }
            }
            return -1;
        };

        return function(v) {
            var i, l;
            if (typeof v != "function") {
                return old.call( this, v );
            }

            l = this.length;

            for( i = 0; i < l; ++i ) {
                if (v.call( this, this[i])) {
                    return i;
                }
            }
            return -1;
        }
})();

arr.indexOf( function(v){return v.color == "blue";} ); //0

arr.indexOf( function(v){return v.images[0].imageData == "xxx"; }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Esailija
  • 138,174
  • 23
  • 272
  • 326
1

Very bad method:

var ind = -1
$(arr).each(function(index, val){if (val.color=='blue'){ind=index;return false;}});

A better way could be to create another map of value which are searchable and their indexes, or something like that.

spicavigo
  • 4,116
  • 22
  • 28