根据匹配的值从数组中删除多个项目

时间:2016-10-12 15:12:17

标签: javascript angularjs

我在根据匹配值从数组中删除项目时遇到问题。我有一个像下面这样的对象数组:

$scope.listOfItems = [
  {productID : 1, weight: 3.5, price: 5},
  {productID : 2, weight: 4.5, price: 8},
  {productID : 3, weight: 1.5, price: 9},
  {productID : 4, weight: 2.5, price: 3},
  {productID : 5, weight: 7.5, price: 1}
];

我想根据productID数组删除项目,如下所示:

$scope.deleteList = [1,3];

现在我尝试使用两个循环来检查productID是否每个产品与deleteList中的任何productID相同。

angular.forEach($scope.listOfItems , function(value, key){
    var tmp_productID = value.productID ;
    var index        = key;
    angular.forEach($scope.deleteList, function(value,key){
        if(tmp_productID === value){
            $scope.listOfItems .splice(index ,1);
        }
    });
}); 
console.log($scope.listOfItems);

问题是,在删除index1后,index3将是index2,因此它会删除product2和product5而不是product2和product4,这是错误的。如果我在数组中有大量对象并且我想删除其中一半,那么性能也会很糟糕。我知道如果可能的话我可以删除正确的记录并提高性能吗?

工作jsfiddle http://jsfiddle.net/Lvc0u55v/10726/

1 个答案:

答案 0 :(得分:1)

您可以反向迭代,这样拼接不会影响之前的指数



var $scope = {};

$scope.listOfItems = [{
    productID: 1,
    weight: 3.5,
    price: 5
}, {
    productID: 2,
    weight: 4.5,
    price: 8
}, {
    productID: 3,
    weight: 1.5,
    price: 9
}, {
    productID: 4,
    weight: 2.5,
    price: 3
}, {
    productID: 5,
    weight: 7.5,
    price: 1
}];

$scope.deleteList = [1, 3];

for ( var i = $scope.listOfItems.length; i--; ) {
    if ( $scope.deleteList.indexOf( $scope.listOfItems[i].productID ) !== -1 ) {
    	$scope.listOfItems.splice(i ,1);
    }
}

console.log($scope.listOfItems);

.as-console-wrapper {top: 0; max-height: 100%!important}




相关问题