简体   繁体   中英

What is the quickest/most efficient way to find the first occurrence index of an object in an list with javascript?

I have an array of objects, at some point the key "a" is populated and continues to be populated for all subsequent objects in the array. What is the fastest and most efficient way to get to that index?

: [{a:null,),{a:null,..},{a:"Value",..},,{a:"Value",..}]

My current method is:

for(var i = 0; i < list.length; i++) {
   if(list[i].a)
      return i;
}
return null;

What is the fastest/smartest way to locate the index where "a" is not null? Is there a better way to do this? Ideal performance should be for lists with large numbers of objects (ie thousands of objects).

I see two ways to do this better/faster, and they both bypass your question.

In the first case, you store a variable that tells you what your first value is; you can do this either when the value is initialized to a non-null, or after the first walk-through to save yourself future walkthroughs.

In the second case, you never initialize the null values of your array and the zeroeth element is always the element you want.

What is the fastest and most efficient way to get to that index?

With regards to efficiency, you're already pretty close to as best as you're going to get. for loops are fast, and you're already breaking out of the iteration once you find a match, which is about all you could hope for.

As mentioned in the comments, however, you could cache the .length value, which is technically faster, but is the very definition of premature/mico-optimization. Just for the sake of thoroughness, though, that would look something like this:

for(var i = 0, len = list.length; i < len; i++) {
    if(list[i].a) return i;
}
return null;

I mentioned earlier in the comments that this approach was "really not that bad... just verbose.", and you asked if it could be "unverbose[d]" (great word, by the way :)). TBH, I don't think there are any especially great ways of doing that. There aren't any built-in "functional" approaches (eg, forEach() , filter() , etc.) that allow breaking out early, and indexOf() doesn't support this kind of a comparison test.

About the best I can offer is some sort of hope for the future here. ES6 introduces the findIndex() method, which when combined with ES6 fat-arrow functions will allow for something like this:

var idx = list.findIndex(item => item.a !== null);

Until then, we basically just have for loops (or I suppose while loops, with no real advantage). :\\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM