I have a table and I’m using AngularJS to display it, there’s a clear button where if clicked all the rows will be deleted from the table. I am using splice to do this but when I try to splice it, only the 1st and 3rd row get splice.
How do I splice all of the rows?
self.row.length = 3; for (var index=0; index < self.row.length; index++) { if (self.row[index].DDelDetailId != 0) { self.deletedRow.push(angular.copy(self.row[index])); } console.log("index: "+index+" Rows: "+self.row.length) self.row.splice(index, 1) }
I already looked at all the similar questions but none of them helped me. It can splice if the self.row.length
is 1 but if it is greater than 1 it leaves 1 row.
Below is what was printed in the console log:
Index: 0 Rows: 3 Index: 1 Rows: 2
I push all the deleted row to self.deletedRow
then if user clicks save then the deleted rows will be deleted in the database. Each row has a delete button so user can delete all rows or delete 1 specific row.
Answer
As you’re moving the index forward while deleting rows, you’re skipping rows: iteration 1:
index = 0 arr: [0, 1, 2] arr.splice(0, 1) => arr: [1, 2] // deletes first item
iteration 2:
index = 1 arr: [1, 2] arr.splice(1, 1) => arr: [1] // deletes second item
iteration 3:
index = 2 arr: [1] arr.splice(2, 1) => arr [1] // tries to delete third item
If you delete the first item all the time, you won’t skip anything:
arr.splice(0, 1)
It’s also more efficient to remove all rows: arr = []
or arr.length = 0
,