Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript indexOf on an array of objects

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"?

like image 927
redconservatory Avatar asked Nov 29 '11 15:11

redconservatory


People also ask

Can I use indexOf with an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

Can we use indexOf for objects in JavaScript?

In this article, we will learn about the indexOf() method in an Object array in Javascript. To access the index of the object from the array having a value of an object, We are going to use a few of the methods. We will understand both methods through the examples.

How do you use findIndex in array of objects?

The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found. The findIndex() method does not execute the function for empty array elements.

Is there an indexOf for arrays?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.


2 Answers

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.

like image 149
Gustavo Rodrigues Avatar answered Sep 20 '22 05:09

Gustavo Rodrigues


for(var i = 0; i < myArray.length; i++) {    if(myArray[i].color === 'blue') {      return i;    } } 

There's no "clean" way unless you want to involve a third-party library. Underscore is a good one for stuff like this.

like image 40
John Strickler Avatar answered Sep 20 '22 05:09

John Strickler