0

I have this.

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"}
];

I want to toggle, remove duplicates from this object on click.

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

How can I do this, any ideas?

Thank in advance :)

Rahi.Shah
  • 1,305
  • 11
  • 20
  • Post the code that you tried. – Prerak Sola Jun 21 '17 at 11:53
  • 1
    Possible duplicate of [Remove Duplicates from JavaScript Array](https://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array) – Prerak Sola Jun 21 '17 at 11:54
  • I just created 2 similar object , first one with duplicates , second one without (filtered) ,and hide/show (switch) them onclick. But its nor the best way i think –  Jun 21 '17 at 12:10

2 Answers2

0

You can call a function which will remove the duplicate from a Array based on any key(in r case its name). pass your studentsList in "originalArray" and name in "prop".

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;
}
0

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;
  }
})
<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>
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26