Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
    
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. – HockeyJ May 22 '15 at 17:03
up vote 2 down vote accepted

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

share|improve this answer
1  
Wow man, that was an elegant solution. May thanks – Joseph Ocasio May 22 '15 at 18:11
$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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.