這裏是我的代碼得到的對象數組的獨特價值:
function toUnique(a, property, innerProperty) {
var lastIndex = a.length;
if (lastIndex === 0 || lastIndex === undefined)
return a;
var copyarr = jQuery.extend(true, [], a);
if (property !== undefined) {
while (prevIndex = --lastIndex) {
while (prevIndex--) {
var obj1 = copyarr[lastIndex];
var obj2 = copyarr[prevIndex];
if (obj1 !== undefined) {
if (copyarr[lastIndex][property] instanceof Array && copyarr[prevIndex][property] instanceof Array)
unique(copyarr[lastIndex][property], copyarr[prevIndex][property], innerProperty);
else
obj1[property] !== obj2[property] || copyarr.splice(prevIndex, 1);
}
}
}
return copyarr;
} else {
while (prevIndex = --lastIndex)
while (prevIndex--)
copyarr[lastIndex] !== copyarr[prevIndex] || copyarr.splice(prevIndex, 1);
return copyarr;
}
}
function unique(array1, array2, innerProperty) {
for (var i = 0; i < array1.length; i++) {
removeDuplicates(array1, i + 1, array1[i], innerProperty);
removeDuplicates(array2, 0, array1[i], innerProperty);
}
for (var i = 0; i < array2.length; i++) {
removeDuplicates(array2, i + 1, array2[i], innerProperty);
}
}
function removeDuplicates(arr, startPos, p, property) {
for (var i = startPos; i < arr.length;) {
if (p[property] == arr[i][property]) {
arr.splice(i, 1);
} else {
i++;
}
}
}
使用:
var a = [{id: 1, title: "AAAA"}, {id: 2, title: "BBBB"}, {id: 1, title: "AAAA"}]
unique(a, "title", null); //return {id: 1, title: "AAAA"}, {id: 2, title: "BBBB"}
var b = [{id: 1, title: "AAAA", authors: [{id: 15, name: "John"}, {id: 25, name: "Peter"}, {id: 16, name: "John"}]},
{id: 1, title: "BBBB", authors: [{id: 15, name: "John"}, {id: 25, name: "Peter}]}]
unique(b, "authors", "name") //return: [{id: 1, title: "AAAA", authors: [{id: 15, name: "John"}, {id: 25, name: "Peter}]},
{id: 1, title: "BBBB", authors: []}]
'angular.copy()'角度的方式。 – Jai
我認爲如果您將某些操作陣列的邏輯移動到控制器,您的問題就會消失。嘗試將調用移動到唯一的(data.items,field)到控制器函數。如果您可以減少ng-repeat中的一個,這將顯着減少消化循環的次數。 – Matt
另一個角度的方法可能是使用$ filter('filter')或爲ng-repeat創建一個自定義過濾器。 – Matt