Most efficient way to find all objects in between two indexes

时间:2018-03-25 19:08:34

标签: javascript algorithm sorting

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)

2 个答案:

答案 0 :(得分:0)

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)
}

答案 1 :(得分:0)

根据这些答案和我的测试,我的原始代码已经充分优化了。其他人给出了答案,无论是缩短它还是更容易阅读。