javascriptangularjs

Remove the duplicate values before pushing into an array


enter image description here

It's visible in the image that the array[0] and array[3], array1 and array[4] are same. I was checking why the values are duplicating but I failed. So thought to just remove if any duplicate values exists. I need to remove it from $scope.arr array itself.

Code:

  $scope.arr = [];
planReq.then(function (callplanList) {
    $scope.callplanList = callplanList.data.callplans;
    //console.log($scope.callplanList);
    for(var i = 0; i < $scope.planMapping.length; i++){
        //console.log($scope.planMapping[i].PlanScode);         
        for(var j = 0; j < $scope.callplanList.length; j++){                
            if(($scope.planMapping[i].PlanScode == $scope.callplanList[j].un_s_code) && ($scope.callplanList[j].offer_type == "REC")){
                //console.log($scope.devicesList);
                for(var a = 0; a < $scope.callplanList[j].upfront_cost.length; a++){
                    if($scope.callplanList[j].upfront_cost[a].upfront != ""){
                        //console.log($scope.callplanList[j].upfront_cost[a].handsetClass);
                        for(var k = 0; k < $scope.devicesList.length; k++){
                            if($scope.callplanList[j].upfront_cost[a].handsetClass == $scope.devicesList[k].device_class.toLowerCase()){
                                $scope.arr.push($scope.devicesList[k]);                                 
                            }
                        }
                    }
                }
            }
        }
        
        
    }
    console.log($scope.arr);
});

Solution

  • Make use of filter.

    Here is a simple filter, to remove duplicates from an array

    Array.filter(function(elem, index, self){ return self.indexOf(elem) == index })

    In your case it will be

    $scope.arr =  $scope.arr.filter(function(elem, index, self){ 
                                      return self.indexOf(elem) == index 
                                    });