10

Using an angular array how do I add and remove elements between the two arrays? I have $scope.results and $scope.list the results array is the result of a call to a WebAPI and i'm allowing the user to select the elements they want to add to the second array. How do i add from the first to the second and remove from the first at the same time?

    angular.forEach($scope.results, function (item) {
        if (item.selected) {
            $scope.list.push(item);
            //CODE TO REMOVE item from $scope.results here.
        };
    });

Additionally if i did a second search and tried to add the same member from the first array to my second array (which already had this user) how do i prevent adding duplicates to the second array (list)?enter image description here.

below is a sample of the objects im wanted to transfer between the arrays. the id field is the indicator of uniqueness.

Joshua
  • 3,261
  • 2
  • 19
  • 33
Tim
  • 7,111
  • 12
  • 57
  • 98
  • You can take a look at the array operations, push, pop, splice, some, etc... If your have more specific question please prepare a demo and show us more code which throws in more context. – PSL Sep 27 '14 at 21:48
  • i dont believe this is duplicate as its angular arrays which add haskeys and their own id's and as stated below splicing reindexes the array. in addition i have the query of id as the indicator of uniqueness. – Tim Sep 27 '14 at 22:08
  • use track by id in your repeat, you won't have haskkey associated anymore. – PSL Sep 27 '14 at 22:12

1 Answers1

4

You can get index as second parameter of angular.forEach. Then us splice to remove the item from original array. Check the code below.

            angular.forEach($scope.results, function (item, index) {
                if (item.selected) {
                    $scope.list.push(item);
                    $scope.results.splice(index, 1);
                };
            });

I just realized there is a drawback in using splice inside angular.forEach loop that it will reindex the array after removing the item. So the immediate next item will be skipped if an item is removed.

So below would be the right solution.

var len = $scope.results.length;
while (len--) {
    var item = $scope.results[len];
    if (item.selected) {
       $scope.list.push(item);
       $scope.results.splice(len, 1);
    };
}

Thanks.

Subash Selvaraj
  • 3,365
  • 1
  • 12
  • 17