2017-08-31 2 views
1

Ich habe den folgenden Code in dem ich lokalen Speicher verwenden Reihe von Produkt varient ID zu speichern, wenn Benutzer auf jeder Produktbeschreibung Seite Treffer Compre .:Wie doppelte Elemente in ihrem Umfang vorhanden entfernen variable

„Prdvar“ Produkt enthält Varianten-IDs (ex: 10,13 usw.)

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)); 

    }; 

Meine Frage ist, wie doppelte Elemente in $ scope.dataVarID zu entfernen.

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

// ich bei dontknow erste, fügt dann 12,13,12,12

Ich brauche nur ,{ ProductVarient :5},{ ProductVarient :33}

Antwort

0

Sie können Karte verwenden und die Duplikate herauszufiltern

//$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

Parameter Funktion ist $ scope.dataVarID.? –

+0

$ scope.dataVarID ist das Array mit doppelten Werten? Wenn ja, ja. – Vivz

+0

TypeError: [Objekt Array] ist keine Funktion, um Fehler zu bekommen. –

0

Verwenden http://underscorejs.org/

zu einem Projekt einbeziehen, diese Bibliothek ist sehr hilfreich für die Array-Manipulationen.

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