2

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);
                }
            }
        };
fresher
  • 399
  • 4
  • 23
  • 1
    @MukeshSharma `splice()` alters original array. – alex Mar 11 '16 at 14:14
  • I tried with vm.stdListCope.pop(); ... but still getting one behind – fresher Mar 11 '16 at 14:19
  • Possible duplicate of [Looping through array and removing items, without breaking for loop](http://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop) – Anthony Mar 11 '16 at 14:36

2 Answers2

3

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.

Mukesh Sharma
  • 8,914
  • 8
  • 38
  • 55
0

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!