我有一个Collection,它有两个键,类似于AngularJs模型。
$scope.Collection=[{id:1,name:"A"},{id:1,name:"B"},{id:1,name:"A"},{id:1,name:"C"},{id:2,name:"A"},{id:2,name:"C"},{id:2,name:"A"},{id:3,name:"D"}];
我想删除重复行,如果两个键都具有相同的值并且想要使用AngularJs过滤器而没有重复行的数组。
示例输出应该如下
$scope.Collection=[{id:1,name:"A"},{id:1,name:"B"},{id:1,name:"C"},{id:2,name:"A"},{id:2,name:"C"},{id:3,name:"D"}]
答案 0 :(得分:0)
一个可能的解决方案就是这个(base angularjs):
.filter('remover', function () {
return function ( items ) {
//filtering duplicates...
var filtered = {};
for ( var i = 0; i < items.length; i++ ) {
if(filtered[items[i].id] == undefined)
filtered[items[i].id] = [];
if(filtered[items[i].id].indexOf(items[i].name) != -1)
filtered[items[i].id].push(items[i].name);
}
//new array with filtered elements
var array = [];
for(var id in filtered){
array.push({id: id, name: filtered[id]});
}
return filtered;
}
} );
这应该是Θ(2n),因为你对数组进行了两次迭代:谨防使用大量数据。
答案 1 :(得分:0)
这是检查给定两个键名称的Angular过滤器,如果两个键名称值在两行中都相同,则从返回的输出集合中删除一行。
.filter('unique2', function () {
return function (collection, keyname1, keyname2) {
var output = [],
keys = [];
for (row = 0; row < collection.length; row++) {
var num1 = collection[row][keyname1];
var num2 = collection[row][keyname2];
for (otherrow = row + 1; otherrow < collection.length; otherrow++) {
var otherrow_index = otherrow;
if (num1 == collection[otherrow_index][keyname1] && num2 == collection[otherrow_index][keyname2]) {
collection.splice(otherrow, 1);
otherrow--;
}
}
}
return collection;
};
});