1

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
3
  • 1
    indexOf is looking for a reference to the same object - they're not. Do you want to delete by id? or perhaps only when id and name match? Commented Feb 16, 2015 at 13:03
  • by id would be fine (some text to fill in the required length of this input) Commented Feb 16, 2015 at 13:04
  • 1
    Then your answer is already below. :) Commented Feb 16, 2015 at 13:06

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

@phari - it actually works, am I doing something so wrong that it went right? :)) Alexander - you're the king of everything! :)) thanks a lot!
@phari - well, it is not really "a", it is users, and I get all the users from the db. I have changed the above code a bit into: userIds = users.map(...); and return userIds.indexOf(item.id) === -1;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.