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/
<>and create a minimal reproducible exampleforloop in reverse?