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}
];
$scope.deleteList = [1,3];
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);
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}