简体   繁体   中英

Most efficient way to find all objects in between two indexes

Assuming you had data like this

var data = [
  {id: 4},
  {id: 0},
  {id: 3},
  {id: 2},
  {id: 1}
]

And this maps to some UI like rows in a table. A user clicks on id:0 then the user clicks on id:2, how do I get all items in between those two IDs? The part I'm trying to figure out is how to do this efficiently because the datasets here can be quite large (10s of thousands).

My best answer to this is the following but wondering if there's any faster methods to this:

var startIndex, endIndex;

for (var i = 0; i < data.length; i++) {
    if (firstElement == data[i].id) {
      startIndex = i;
    }
    if (lastElement == data[i].id) {
      endIndex = i;
    }
    if (startIndex !== undefined && endIndex !== undefined) {
      break;
    }
} 

var newData = data.slice(startIndex, endIndex + 1)

Tens of thousands is not that large for an O(n) scan, and you can't do better than O(n) since you need to look at each item.

To make the code a little cleaner, you can use findIndex to start from there

let startIndex = data.findIndex({ id } => id === firstElement), endIndex;
let endIndex;
for (var endIndex = startIndex; data[endIndex].id !== lastElement; i++) {
  if (endIndex === data.length) { endIndex = -1; break; }
}
if (endIndex !== -1) {
  var newData = data.slice(startIndex, endIndex + 1)
}

Based on these answers and my testing my original code is plenty optimized already. The others gave answers really around either shortening it or making it easier to read.

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