要得到一个特定的对象和数组不用循环最好的方法 [英] 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
// from the resource within the controllers scope
$scope.xyz = data.objects;
});
现在 $ scope.xyz
看起来像
[
0: {id: 1, ...more data here ...},
1: {id: 2, ...more data here ...},
2: {id: 3, ...more data here ...},
3: {id: 4, ...more data here ...},
4: {id: 5, ...more data here ...},
5: {id: 6, ...more data here ...},
]
我所试图做的是使用 ID
属性(不在名单指数)获得XYZ中的一个对象。我知道我可以在阵列上迭代如下:
What i am trying to do is get an object within xyz using the id
property (not the list index). I am aware that I can iterate over the array as follows.
angular.forEach($scope.xyz, function(obj){ return obj.id == 1;});
但有一种方法,我可以不用循环在列表?
but is there a way I can do it without looping over the list ?
推荐答案
没有,你真的不能避免循环( O(N)
),除非有一些preconditions满足。
No, you can't really avoid looping (O(n)
) unless there are some preconditions met.
- 如果该阵列由ID排序,您可以使用二进制搜索算法(
O(log n)的
)。 - 如果数组索引总是对应于ID-1(或一些类似的简单的公式),可以直接访问它
O(1)
。
- 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)
.
如果这些条件不能满足最初,但是你需要通过ID多次访问该项目时,它可帮助使他们以这样的形式(整理/建筑哈希映射)。
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).
这篇关于要得到一个特定的对象和数组不用循环最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!