[removed] move objects from one array to another: Best approach?

后端 未结 7 638
臣服心动
臣服心动 2021-01-04 01:38

I have two arrays, called \'objects\' and \'appliedObjects\'. I\'m trying to come up with an elegant way in Javascript and/or Angular to move objects from one array to anot

7条回答
  •  借酒劲吻你
    2021-01-04 02:04

    You are altering the array while iterating on it, you will always miss some elements.

    One way of doing it would be to use a third array to store the references of the objects that need to be removed from the array:

    // "$scope.add" case
    var objectsToRemove = [];
    
    $scope.objects.forEach(function (value) {
      if (value.selected) {
        value.selected = false;
        $scope.appliedObjects.push(value);
        objectsToRemove.push(value);
      }
    });
    
    objectsToRemove.forEach(function (value) {
      $scope.objects.splice($scope.objects.indexOf(value), 1);
    });
    

提交回复
热议问题