Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add and remove items between arrays in angular [duplicate]

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.

like image 513
Tim Avatar asked Sep 27 '14 21:09

Tim


People also ask

How do you remove duplicate objects from an array?

To remove the duplicates from an array of objects: Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


1 Answers

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.

like image 98
Subash Selvaraj Avatar answered Oct 27 '22 00:10

Subash Selvaraj