0

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);
      }
    });
  }
3
  • 1
    splice won't work in a forEach loop, since every time you splice, you affect the indexes of the undeleted items (see Why isn't splice working in this for loop?). Instead, reduce or filter your array to a new array without the items. Commented Dec 8, 2023 at 17:13
  • @HereticMonkey: Can you update your answer in the stackblitz? Commented Dec 8, 2023 at 17:43
  • I don't have an answer. I made two comments. One with a reason why it wasn't working and a suggestion, a second pointing to a question that asks essentially the same question. I'm not going to apply the duplicate's answers to your problem. Do that yourself. If you are unable to, ask a new question showing what you tried and the errors you get when you do so. Commented Dec 8, 2023 at 17:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.