如何使用AngularJS获取具有唯一值的数组

时间:2016-01-25 10:43:00

标签: javascript angularjs

我有一个包含重复项的数组。如何获得包含唯一项目的数组?

a= [{id: "1", campus: "c1"}, {id: "1", campus: "c1"}, {id: "2", campus: "c2"}, {id: "2", campus: "c2"}]

我想要带有唯一对象的结果

a= [{id: "1", campus: "c1"}, {id: "2", campus: "c2"}]

3 个答案:

答案 0 :(得分:3)

您可以使用Array#filter,如下所示:

var arr = [{
    id: "1",
    campus: "c1"
}, {
    id: "1",
    campus: "c1"
}, {
    id: "2",
    campus: "c2"
}, {
    id: "2",
    campus: "c2"
}];

// Keep an array of elements whose id is added in filtered array
var elementId = [];

var newArr = arr.filter(el => {
    if (elementId.indexOf(el.id) === -1) {
        // If not present in array, then add it
        elementId.push(el.id);
        return true;
    } else {
        // Already present in array, don't add it
        return false;
    }
});

console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<pre id="result"></pre>

基于OP的comment

  

请提出有关表现的最佳方式..

如果您对下划线/ lodash

没问题

您可以使用_.uniqWith

_.uniqWith(arr, _.isEqual);

var arr = [{
    id: "1",
    campus: "c1"
}, {
    id: "1",
    campus: "c1"
}, {
    id: "2",
    campus: "c2"
}, {
    id: "2",
    campus: "c2"
}];

var newArr = _.uniqWith(arr, _.isEqual);
console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js"></script>
<pre id="result"></pre>

您也可以使用_.uniqBy

_.uniqBy(arr, 'id');

var arr = [{
    id: "1",
    campus: "c1"
}, {
    id: "1",
    campus: "c1"
}, {
    id: "2",
    campus: "c2"
}, {
    id: "2",
    campus: "c2"
}];

var newArr = _.uniqBy(arr, 'id');
console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js"></script>
<pre id="result"></pre>

答案 1 :(得分:1)

Angular jqLit​​e实现不包含$ .filter函数。

您必须提供自己的实施。你可以这样做:

function getUniqueArray(array){
  var result = [];
  for(var x = 0; x < array.length; x++){
  if(result.indexOf(array[x]) == -1)
        result.push(array[x]);
  }
  return result;
}

答案 2 :(得分:1)

您可以使用AngularUI

中的unique
<li ng-repeat="x in myArr | unique:id">
  {{ x.campus }}
</li>

DEMO