0

I have this AngularJS service.

demoService.getDemoData($scope.countEP).then(function (data) {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    $scope.allEditorPicks.push(data[i]);
                }
            });

In this case,allEditorPicks is an array i have defined at the top of the code as follows.

$scope.allEditorPicks = [];

Here's the problem, when I'm using this array and printing these data, the array has same items. Duplicating. So I need a way to check existing items and stop adding them in that allEditorPicks array. We need to do this inside the for loop. I tried adding another loop inside the for loop and read the allEditorPicks array and check. But that doesn't work too.

demoService.getDemoData($scope.countEP).then(function (data) {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    for (var j = 0; j < $scope.allEditorPicks.length; j++) {
                        if ($scope.allEditorPicks[j].itemName == data[i].itemName) {
                            console.log("Item Exists")
                        } else {
                            $scope.allEditorPicks.push(data[i]);
                        }
                    }
                }
            });

This is the solution I tried. My browser got freezes and stopped working when I run this code. Please give me a solution.

Chanaka De Silva
  • 401
  • 9
  • 20
  • Possible duplicate of [How to make ng-repeat filter out duplicate results](http://stackoverflow.com/questions/15914658/how-to-make-ng-repeat-filter-out-duplicate-results) – hurricane May 12 '17 at 14:41

2 Answers2

0

first, sort the array by itemName and then remove the duplicates according to the order.

data = data.sort(function(a,b){
 return a.itemName - b.itemName;
});

for (var i = 0; i < data.length; i++) {
   if(data[i].itemName === data[i++].itemName){
       console.log("Item Exists");
   }else {
        $scope.allEditorPicks.push(data[i]);
   }           
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

Try this :

demoService.getDemoData($scope.countEP).then(function (data) {
  for(let i = 0; i < data.length; i++){
   let found = $scope.allEditorPicks.find(elt => {
      return elt.itemName === data[i].itemName;
   });
   if(!found){
      $scope.allEditorPicks.push(data[i]);
   }
  }
})
Dimitri
  • 8,122
  • 19
  • 71
  • 128