Best Way To Get A Specific Object From And Array Without Looping
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 the data retrieved
Solution 1:
Though this is already answered a year ago, since this is one of the top results in Google, I thought I can add the following suggestion which may be the easiest way to filter. After injecting $filter into your controller,
var result = $filter('filter')($scope.xyz, {id:"1"});
Solution 2:
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).
Post a Comment for "Best Way To Get A Specific Object From And Array Without Looping"