Might be duplicate, but I couldn't find it. So I have two arrays of objects:
var a = [{id: '1', name: 'bob'}, {id: '2', name: 'bill'}]
$scope.b = [{id: '4', name: 'jack'}, {id: '2', name: 'bill'}, {id: '1', name: 'bob'}, {id: '3', name: 'john'}]
I want to remove all the a elements from b. I have tried:
$scope.b = $scope.b.filter(function(item){
return a.indexOf(item) === -1;
});
unfortunately, for some reason, the index is always -1, so nothing gets deleted. with some console.log-s
console.log(item);
console.log(a);
console.log(a.indexOf(item));
, this is how the data looks like:
Resource {id: 4, name: "jack"}
[Resource, Resource, Resource, Resource, $promise: Promise, $resolved: true]
-1
You can do it like this
// get all id's from a
var a = [{id: '1', name: 'bob'}, {id: '2', name: 'bill'}].map(function (el) {
return el.id;
});
// search item.id in array with id's
$scope.b = $scope.b.filter(function(item){
return a.indexOf(item.id) === -1;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.