2017-08-31 73 views
1

我有下面的代码中,我使用的本地存储来存储产品的变体光盘ID的阵列时,用户点击每个产品介绍页面上COMPRE:如何删除重复的项目出现在范围变量

“Prdvar”包含产品ID变型的(例如:10,13等)

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

    }; 

我的问题是如何去除存在于$ scope.dataVarID重复的项目。

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

//我dontknow在 首先,是增加再12,13,12,12

我只需要,{ ProductVarient :5},{ ProductVarient :33}

回答

0

您可以使用地图和过滤掉重复的

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

参数的功能是$ scope.dataVarID? –

+0

$ scope.dataVarID是包含重复值的数组吗?如果是这样,是的。 – Vivz

+0

TypeError:[对象数组]不是一个获取错误的函数。 –

0

使用http://underscorejs.org/

包括对您的项目中,该库是数组操作非常有帮助。

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