What\'s the best method to get the index of an array which contains objects?
Imagine this scenario:
var hello = {
hello: \'world\',
foo: \'ba
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, using filter
.
element = myArray.filter((e) => e.hello === 'stevie')[0];
See perfomance results (~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3