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);
}
}
});
}
asked Sep 21, 2015 at 6:31
Gaurav123
5,2296 gold badges57 silver badges81 bronze badges
1 Answer 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
};
answered Sep 21, 2015 at 6:34
Cerbrus
73.3k19 gold badges138 silver badges151 bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
Deblaton Jean-Philippe
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.
Rayon
Filter inside
foreach using some different conditions as OP mentioned ?Cerbrus
@DeblatonJean-Philippe: That is simply not true. Angular can handle
filter just fine, I use it all the time -.-New Dev
@DeblatonJean-Philippe, what exactly would "confuse" Angular?
Cerbrus
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. |
lang-js