0

I have an array of objects. I want to remove multiple objects from that array.

I have used below code which is working absolutely fine, but I need to check with you guys if there is better way to do that or its fine.

I have done it with angularjs and js.

Orders is the main array on which operations are performed. Order is array of selected items to remove from main array Orders

$scope.Order = {};
$scope.removeOrders = function () {
        angular.forEach($scope.Order, function (data) {
            for (var i = $scope.Orders.length - 1; i >= 0; i--) {
                if ($scope.Orders[i].Name == data.Name) {
                    $scope.Orders.splice(i, 1);
                }
            }
        });
        }

1 Answer 1

1

You can make it quite a bit shorter using filter:

$scope.removeOrders = function () {
    $scope.Orders = $scope.Orders.filter(function(order){
        return !$scope.Order.some(function(remove){
            return remove.Name === order.Name;
        });
    }); // remove the order from $scope.Orders, if it's name is found in $scope.Order
};
Sign up to request clarification or add additional context in comments.

9 Comments

I don't like this approach. array.filter() creates a new array with a new reference, which will confuse AngularJs, and you will have issues with the update of the view. Also, if this object is referenced else where, the other object won't be updated.
Filter inside foreach using some different conditions as OP mentioned ?
@DeblatonJean-Philippe: That is simply not true. Angular can handle filter just fine, I use it all the time -.-
@DeblatonJean-Philippe, what exactly would "confuse" Angular?
order is an item in $scope.Orders. the OP is comparing $scope.Orders[i].Name. So no, @Satpal. it shouldn't be indexOf(order). That said, like this can't work, either. editing my code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.