How to remove duplicate items present in scope variable

434 Views Asked by At

I have the following code in which I used local storage to store array of Product varient ID when user hits compre on every product description page.:

"Prdvar" contains product variants ID's (ex: 10,13, etc.,)

a.push(JSON.parse(localStorage.getItem('session')));
    localStorage.setItem('session', JSON.stringify(a));
    $scope.dataVarID = JSON.parse(localStorage.getItem('session'));

    alert($scope.dataVarID); //Duplicate values present

    $scope.CompareProduct = function()  {

        a = JSON.parse(localStorage.getItem('session'));
        a.push("{ ProductVarient :"+Prdvar+"}");
        alert(a);
        localStorage.setItem('session', JSON.stringify(a));

     };

My question is how to remove duplicate items present in $scope.dataVarID.

,{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :33}

// I dontknow at first , is adding then 12,13,12,12

I need only ,{ ProductVarient :5},{ ProductVarient :33}

3

There are 3 best solutions below

5
Vivz On BEST ANSWER

You can use map and filter out the duplicates

//$scope.dataVarID = JSON.parse(localStorage.getItem('session'));
function getUniqueArrayObject(array) {
    var result = array.map(function(a) {
        return a.ProductVarient;
    });
    var unique = [];
    for (var x = 0; x < result.length; x++) {
        if (unique.indexOf(result[x]) == -1) unique.push(result[x]);
    }
    return (unique.map(function(a) {
        return {
            ProductVarient: a
        };
    }))
}
var newArray = getUniqueArrayObject([{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :33}])
console.log(newArray)
// $scope.newArray=getUniqueArrayObject($scope.dataVarID);

0
bertrandg On

Not related to angular,

I recomment you to use lodash uniq function to do that: https://lodash.com/docs/4.17.4#uniq

0
AudioBubble On

Use http://underscorejs.org/

Include to your project, this library is very helpful for array manipulations.

var arrray = [{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :5},{ ProductVarient :33}]

var result = _.map(_.groupBy(ar,function(doc){
  return doc.ProductVarient;
}),function(grouped){
  return grouped[0];
});

Result is: [{ ProductVarient :5},{ ProductVarient :33}]