I have an array like this:
[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]
How can I get the index of the object that matches a condition, without iterating over the entire array?
For instance, given prop2=="yutu"
, I want to get index 1
.
I saw .indexOf()
but think it's used for simple arrays like ["a1","a2",...]
. I also checked $.grep()
but this returns objects, not the index.
Best Answer
As of 2016, you're supposed to use
Array.findIndex
(an ES2015/ES6 standard) for this:It's supported in Google Chrome, Firefox and Edge. For Internet Explorer, there's a polyfill on the linked page.
Performance note
Function calls are expensive, therefore with really big arrays a simple loop will perform much better than
findIndex
:As with most optimizations, this should be applied with care and only when actually needed.