best way to get a specific object from and array without looping

前端 未结 2 1349
日久生厌
日久生厌 2021-01-20 20:03

In one of the controllers of my angular application i have a variable set as follows.

SomeService.get({}, function(data){
    // this sets xyz as the list of         


        
2条回答
  •  既然无缘
    2021-01-20 20:34

    No, you can't really avoid looping (O(n)) unless there are some preconditions met.

    • If the array is sorted by id, you can use a binary search algorithm (O(log n)).
    • If the array index always corresponds to the id-1 (or some similar simple formula), you can directly access it in O(1).

    If those conditions are not fulfilled initially, but you need to access the items by id multiple times, it could be helpful to bring them in that form (sorting/building a hash map).

提交回复
热议问题