0

I want to add data into a new array and remove data from the current list on a button click. Right now it only removes the last item and sometimes two checked items not 4-6 items.

$scope.LoadBack = function () {
  for (var i = 0; i < $scope.MyArrold.length; i++) {
    if ($scope.MyArrold[i].checked == true) { 
      $scope.BackList.push(angular.extend({}, $scope.MyArrold[i]));            
      var index = $scope.MyArrold.indexOf($scope.MyArrold[i]);
      $scope.MyArrold.splice(index, 1);
    }
  }
}
1
  • just add i--; after you splice the array. Commented Oct 22, 2018 at 7:51

2 Answers 2

1

You're removing items from the array while you are in a loop which is iterating over the array. That doesn't work.

One way to solve this is to add the items you want to keep to a temp array and then assign that array back to MyArrold after the loop completes.

Another way to solve this is to track the indexes you wish to remove in a temp array, and then iterate over this array after the loop completes, backwards! To use this solution you have to iterate backwards else all future indexes become invalid.

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

Comments

0
var i = $scope.MyArrold.length;
while (i--) {
   if ($scope.MyArrold[i].checked === true) {          
      $scope.MyArrold.splice(i, 1);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.