Search code examples
javascriptarraystypescriptangular13

How to remove multiple object from an array in angular 13


Tried to delete multiple object from an array by selecting the checkbox table row. But in my code only 1 item is deleted. Not able to delete multiple selection object. How to resolve this issue?

Demo: https://stackblitz.com/edit/angular-ivy-fflhjh?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

app.component.ts:

  removeSelectedRow() { 
    this.data2.forEach((value, index) => {
      console.log(value);
      if (value.isSelected === true) {
        this.data2.splice(index, 1);
      }
    });
  }

Solution

  • You can use Array.filter and Array.Includes archieve the result you need. Refer the below code for more reference:

    let items = [
      { id: 1, name: 'Item 1' },
      { id: 2, name: 'Item 2' },
      { id: 3, name: 'Item 3' },
      { id: 4, name: 'Item 4' },
      { id: 5, name: 'Item 5' }
    ];
    
    
    const itemsToRemove = [2, 4]; // Array of item IDs to be removed
    
    
    items = items.filter(item => !itemsToRemove.includes(item.id));
    
    console.log(items);