我确信之前会问这个问题,但由于某种原因,我无法找到正确的方法来找到我之后的答案。
我有两个对象列表。对象略有不同,但都有一个' ref'我可以比较它们的财产。我基本上想要一个新的对象列表,它只包含list1中的对象,其ref值不等于list2中对象的任何ref值。
目前这是我使用的方法。 这确实有效。但是我知道这可能是非常低效的,因为我使用两个循环并循环遍历第二个无数次。所以我想知道什么是正确的'这样做的方法是。
var add;
for (var x = 0; x < availableQuestions.length; x++) {
add = true;
for (var j = 0; j < currentQuestions.length; j++) {
if (availableQuestions[x].Ref == currentQuestions[j].Ref) {
add = false;
}
}
if (add) {
$scope.Questions.push(availableQuestions[x])
}
}
答案 0 :(得分:2)
在当前问题中创建ref
数组,只需要迭代该数组一次。
然后过滤另一个数组,与Ref
数组相比较var currentRef = currentQuestions.map(function(item){
return item.Ref;
});
$scope.Questions = availableQuestions.filter(function(item){
return currentRef.indexOf(item.Ref) === -1;
});
甚至更快的是一个hashmap对象,其中item.Ref
是属性名称
var currentRef = currentQuestions.reduce(function(obj,item){
obj[item.Ref] = true;
return obj;
},{});
$scope.Questions = availableQuestions.filter(function(item){
return !currentRef[item.Ref];
});
注意:所有这些方法都返回新数组,因此不会破坏原始数组
答案 1 :(得分:0)
试试这个:
for (var x = 0; x < availableQuestions.length; x++) {
for (var j = 0; j < currentQuestions.length; j++) {
if (availableQuestions[x].Ref == currentQuestions[j].Ref) {
$scope.Questions.push(availableQuestions[x]);
}
}
}
答案 2 :(得分:0)
如果您可以访问Set
,则可以执行以下操作:
var s = new Set(currentQuestions.map(function(q) { return q.Ref }));
availableQuestions.forEach(function(q){
if(!s.has(q.Ref)){
$scope.Questions.push(q);
}
});
这假设aq.Ref === cq.Ref
答案 3 :(得分:0)
将两个数组转换为关联数组,然后您可以执行一次传递以获得不匹配的数组:
var avail = new Array();
var curr = new Array();
angular.forEach(availableQuestions, function(q){
avail[q.Ref] = q;
});
angular.forEach(currentQuestions, function(q){
curr[q.Ref] = q;
});
angular.forEach(avail, function(a){
var q = curr[a.Ref];
if (q !== null) {
$scope.Questions.push(a);
}
});