在AngularJS中单击时删除重复项

时间:2017-06-21 11:52:46

标签: angularjs duplicates

我有这个。

var studentsList = [
    {"Id": "101", "name": "One"},
    {"Id": "101", "name": "One"},
    {"Id": "102", "name": "Two"},
    {"Id": "103", "name": "Three"},
    {"Id": "103", "name": "Three"},
    {"Id": "104", "name": "Four"},
    {"Id": "104", "name": "Four"}
];

我想在点击时切换,从此对象中删除重复项。

<button ng-click="removeDuplicates = !removeDuplicates"></button>

我怎么能这样做,有什么想法吗?

提前感谢:)

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
angular.module('app', [])
.controller('MyController', ['$scope', function($scope) {
    $scope.studentsList = [
    {"Id": "101", "name": "One"},
    {"Id": "101", "name": "One"},
    {"Id": "102", "name": "Two"},
    {"Id": "103", "name": "Three"},
    {"Id": "103", "name": "Three"},
    {"Id": "104", "name": "Four"},
    {"Id": "104", "name": "Four"}
];
}]).filter('dupfilter',function(){
  var cache = {};
  return function(array, dup){
    if(dup)
      return array;
      
    var key = JSON.stringify(array);
    if(cache[key])  
      return cache[key];
    
    var temp = [];
    for(var item of array){
      item.$$hashKey = undefined;
      var str = JSON.stringify(item);
      if(temp.indexOf(str) == -1)
        temp.push(str);
    }
    var result = [];
    for(var item of temp)
      result.push(JSON.parse(item));
      
    cache[key] = result;
      
    return result;
  }
})
&#13;
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller="MyController">    
   <input type='button' value='{{(removeDuplicates ? "Allow" : "Remove") + " duplicates"}}' ng-click='removeDuplicates=!removeDuplicates'/>
   <ul>
     <li ng-repeat='item in studentsList | dupfilter: !removeDuplicates'>{{item | json}}</li>
   </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以调用一个函数,该函数将根据任何键(以其名称命名)从数组中删除副本。 将你的学生列表传递给&#34; originalArray&#34;并在&#34; prop&#34;中命名。

removeDuplicates(originalArray, prop) {
    var newArray = [];
    var lookupObject  = {};

    for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
    }

    for(i in lookupObject) {
        newArray.push(lookupObject[i]);
    }
    return newArray;
}