-1

------Edited---------------

I have 2 arrays of objects A, B

var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:3}];

I want to delete object which are both in A and in B

//after the operation
 a = [{id:1},{id:2},{id:3}];

I thought in order to do it, I need to get the index of them in A to use A.splice() but I just cannot wrap my head around how I can do it.

This is the code I use to get the objects itself from Difference between two array of objects in JavaScript

 var onlyInA = A.filter(function(current){
    return res.nodes.filter(function(current_b){
        return current_b._id == current._id
    }).length == 0
Community
  • 1
  • 1
Loredra L
  • 1,485
  • 2
  • 16
  • 32

2 Answers2

2

Filter in filter would not be the way to go. You want to use filter and some.

var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:5},{id:6},{id:7}];

var result = a.filter( function(oa) {
  return b.some( function(ob){
    return oa.id===ob.id;
  });
});

a.length = 0;
a.push.apply(a, result);

console.log(JSON.stringify(a));

If you want to use splice(), than loop over it backwards.

var a = [{id:1},{id:2},{id:3},{id:4},{id:5}];
var b = [{id:1},{id:2},{id:5},{id:6},{id:7}];

for (var i=a.length-1;i>=0;i--) {
    var inB = b.some( function(ob){
      return a[i].id===ob.id;
    });
    if(!inB) {
      a.splice(i,1)
    }
}
console.log(a);
epascarello
  • 204,599
  • 20
  • 195
  • 236
2

You could use a hash table for the id of the objects and filter a with it.

var a = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
    b = [{ id: 1 }, { id: 2 }, { id: 3 }],
    hash = Object.create(null);

b.forEach(function (item) {
    hash[item.id] = true;
});

a = a.filter(function (item) {
    return hash[item.id];
});

console.log(a);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392