1

Hello dear Stackoverflow Community

I have encouraged some strange behavior when using splice on my array. I splice the array "tempFilterdProduts" but also the array "this.products" seems to be affected. As a console.log shows the array "this.products" is getting shorter. Is there anything I'm missing here? Any help would be much appreciated! I'm using Angular 12

let tempFilterdProduts = this.products
let itemsToDelete: number[] = [];
let tempCategoryFilterList: number[] = []
this.allCategoriesCheckBox.forEach(ategoriesCheckBox => {
  if (!ategoriesCheckBox.checked) {
    tempCategoryFilterList.push(ategoriesCheckBox.id);
  }
});

let index: number = 0;
tempFilterdProduts.forEach(fProduct => {
  if(tempCategoryFilterList.includes(fProduct.CategegoryId)){
    itemsToDelete.push(index);
  }
  index++;
});
for(var i = itemsToDelete.length-1; i >= 0; i--){
  tempFilterdProduts.splice(itemsToDelete[i], 1);
}
this.filterdProduts = tempFilterdProduts;

}

Silas
  • 39
  • 7
  • 4
    You'll want to look into "shallow vs deep copy" (e.g. https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy). What you're doing there is to create another reference to the same data. And if you modify the new copy, the copied element is affected as well. Something like `let tempFilterdProduts = JSON.parse(JSON.stringify(this.products))` should yield the kind of copy you're looking for. – Aldin Bradaric Feb 10 '22 at 13:44
  • @Aldin Bradaric Thanks! That was actually really helpful – Silas Feb 10 '22 at 13:48
  • if the two array lengths are not the same then can be a problem – Siddhartha Mukherjee Feb 10 '22 at 13:51

0 Answers0