What's the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello,qaz);
Now I would like to have the indexOf
the object which hello
property is 'stevie'
which, in this example, would be 1
.
I'm pretty newbie with JavaScript and I don't know if there is a simple method or if I should build my own function to do that.
Use
_.findIndex
from underscore.js libraryHere's the example
_.findIndex([{a:1},{a: 2,c:10},{a: 3}], {a:2,c:10}) //1
If you are only interested into finding the position see @Pablo's answer.
pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');
However, if you are looking forward to finding the element (i.e. if you were thinking of doing something like this
myArray[pos]
), there is a more efficient one-line way to do it, usingfilter
.element = myArray.filter((e) => e.hello === 'stevie')[0];
See perfomance results (~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3
This is the way to find the object's index in array
Array.prototype.findIndex is supported in all browsers other than IE (non-edge). But the polyfill provided is nice.
The solution with map is okay. But you are iterating over the entire array every search. That is only the worst case for findIndex which stops iterating once a match is found.
There's not really a concise way(when devs had to worry about IE8), but here's a common solution:or as a function:
Just some notes:
For example,