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)?.
below is a sample of the objects im wanted to transfer between the arrays. the id field is the indicator of uniqueness.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With