Remove array of objects from another array of objects

Here is a nice one line answer :)

Basically, you can filter, as you were trying to do already. Then you can also filter b for each a element and if the length of the filtered b is zero, then you return true because that means the a element is unique to a.

var a = [{
  'id': '1',
  'name': 'a1'
}, {
  'id': '2',
  'name': 'a2'
}, {
  'id': '3',
  'name': 'a3'
}];

var b = [{
  'id': '2',
  'name': 'a2'
}];

c = a.filter( x => !b.filter( y => y.id === x.id).length);
console.log(c);

How about this solution? It assumes that 'b' is also an array so for each element of 'a' you check if there is a matching object in 'b'. If there is a matching object then return a false in the filter function so that that element is discarded.

var a = [{
  'id': '1',
  'name': 'a1'
}, {
  'id': '2',
  'name': 'a2'
}, {
  'id': '3',
  'name': 'a3'
}]
var b = [{
  'id': '2',
  'name': 'a2'
}]

var c = a.filter(function(objFromA) {
  return !b.find(function(objFromB) {
    return objFromA.id === objFromB.id
  })
})

console.log(c)

Tags:

Javascript