0

Hello I am having problems of indexes when trying to delete from an array.

 <i class="icon ion-ios-checkmark-outline" ng-click="addToHistory(task.info, task.measured, task.total, task.done, task.id)"  ></i> 
            {{task.info}}
 $scope.addToHistory = function(title, measured, total, done, id) {
     var index = $scope.tasksCollection.indexOf($scope.tasksCollection[id]);
     $scope.tasksCollection.splice(index, 1);
}

the Above works, but when I try to delete the first item, and go for the second one, the third gets deleted instead of the second one. I know is a problem of indexes, but I dont have ideas on how to solve it.

To recap I have:

  • Item1 (index 0)
  • Item2 (index 1)
  • Item3 (index 2)

when I delete the first one I get

  • Item2 (index 0)
  • Item3 (index 1)

and when I try to delete Item2, the index I get back is 1, so Item3 gets deleted.

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
Joseph Ocasio
  • 989
  • 4
  • 10
  • 19
  • Appreciate you may be new to SO. If one/any of these are correct, please mark it as such for the benefit of future searchers. – JsAndDotNet May 22 '15 at 17:03

3 Answers3

2

I think the issue is with using the task.id for the lookup.

Try passing in $index instead.

<i class="icon ion-ios-checkmark-outline" ng-click="addToHistory($index, task.info, task.measured, task.total, task.done, task.id)"  ></i> 
            {{task.info}}

js

$scope.addToHistory = function(index, title, measured, total, done, id) {
     $scope.tasksCollection.splice(index, 1);
}

Docs for index

JsAndDotNet
  • 16,260
  • 18
  • 100
  • 123
1
$scope.tasksCollection[id]

Tries to get the task at index id - now depending on how that id is generated, you could either have something like :

$scope.tasksCollection[123] - which won't make sense (if it's an actual entity id)

or if you set the id property on the client side, once you remove from the collection, the ids won't match.

Use $index for what you want to do like HockeyJ suggested.

sirrocco
  • 7,975
  • 4
  • 59
  • 81
-1

This is a problem with using splice in a loop. Splice reindexes the array and makes length property obsolete. Generally the solution is to run through the array backwards when deleting. See this previous answer for more help.

Looping through array and removing items, without breaking for loop

Community
  • 1
  • 1
kezor
  • 91
  • 7