Alex Rivera | Logout

Javascript indexOf on an array of objects

Asked 2011-11-29T15:27:09.737
53

if I have an array like:

var myArray = [
                {
                    'color':'red',
                    'name': 'redName'
                },
                {
                    'color':'blue',
                    'name': 'blueName'
                },
                {
                    'color':'green',
                    'name': 'greenName'
                    },
                {
                    'color':'yellow',
                    'name': 'yellowName'
                },
             ];

How do I get the index of say, "blue"?

Edit
Report

2 Answers

73

If you're already using ECMAScript 5 in your code you can use that:

myArray
    .map(function (element) {return element.color;})
    .indexOf('blue');

Note that the support to these functions is a quite limited (they don't work on Internet Explorer 8).

Also, if you're in the future, and you're using ES6 you can do that:

myArray.map((el) => el.color).indexOf('blue');

That's the same as above, but smaller.

answered 2013-06-18T19:46:05.477
2

I'm guessing you mean from your example to return "1"? Here is a function for you...

<script type='text/javascript'>
var myArray = [
                {
                    'color':'red',
                    'name': 'redName'
                },
                {
                    'color':'blue',
                    'name': 'blueName'
                },
                {
                    'color':'green',
                    'name': 'greenName'
                    },
                {
                    'color':'yellow',
                    'name': 'yellowName'
                },
             ];
function getIndexOf(a,v) {
  var l = a.length;
  for (var k=0;k<l;k++) {
    if (a[k].color==v) {
        return k;
      }
  }                      
  return false;
}

alert (getIndexOf(myArray,'blue'));
</script>
answered 2011-11-29T15:31:44.730

Your Answer