Reputation: 399
Why my below code leaving one record? It should delete all 3 record from vm.events if my Id=40
vm.events = [
{
"studentId": "40",
"studentName": "P Arjun",
},
{
"studentId": "40",
"studentName": "P Arjun",
},
{
"studentId": "40",
"studentName": "P Arjun",
}
];
vm.setSelectedStudent = function (Id) {
vm.stdListCope = angular.copy(vm.events);
for (var i in vm.stdListCope) {
if (vm.stdListCope[i]['studentId'] == Id) {
vm.stdListCope.splice(i, 1);
}
}
};
Upvotes: 2
Views: 51
Reputation: 54
This happens because you are splicing the array while you are browsing it. Thus, you should not increase the index when deleting a row. Here is a corrected version of your code using a while:
vm.events = [
{
"studentId": "40",
"studentName": "P Arjun",
},
{
"studentId": "40",
"studentName": "P Arjun",
},
{
"studentId": "40",
"studentName": "P Arjun",
}
];
vm.setSelectedStudent = function (Id) {
vm.stdListCope = angular.copy(vm.events);
for (var i = 0; i < list.length; i++) {
while (vm.stdListCope[i] != undefined && vm.stdListCope[i]['studentId'] == Id) {
vm.stdListCope.splice(i, 1);
}
}
};
Hope it helps!
Upvotes: 0
Reputation: 9022
There is a bug in your code.
When it runs for i=0
, vm.stdListCope.splice(0, 1);
slices the array to the array with single entry.
So, after i=0
, vm.stdListCope
has [{"studentId": "40", "studentName": "P Arjun", }]
But, when the loop runs for i=1
or i =2
, vm.stdListCope[i]['studentId'] == Id
won't be true, because there is not entry corresponding to index i=1
and i=2
as it has length = 1.
That's why you are left with only 1 entry.
Upvotes: 3