Jaaaaaaay Jaaaaaaay - 1 month ago 17
AngularJS Question

Remove multiple items from array based on matched value

I have issues removing items from an array based on matched value. I have an array of object like below:

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


And I want to remove items based on an array of productID, like below:

$scope.deleteList = [1,3];


Now I try to use two loops to check if the productID if each product is the same with any productID in the deleteList.

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


The problem of this is, after it deletes the one with index1, the index3 will be index2, thus it will delete product2 and product5 instead of product2 and product4, which is wrong. Also the performance will be bad if I have a large number of objects in the array and I want to delete half of them. Any idea that I can delete the right record and improve the performance if possible?

Working jsfiddle
http://jsfiddle.net/Lvc0u55v/10726/

Answer

You could iterate in reverse, that way the splicing won't affect the previous indices

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}

Comments