Remove all elements from an array that already exist in another

Asked

Viewed 2,251 times

3

I have two arrays with javascript objects:

var a = [{objeto1}, {objeto2}, {objeto3}, {objeto4}, {objeto5}];
var b = [{objeto1}, {objeto2}];

How to do what is in the array b exit the array a?

6 answers

5


you can do next.:

var objeto1 = { value: 'A' };
var objeto2 = { value: 'B' };
var objeto3 = { value: 'C' };
var objeto4 = { value: 'D' };
var objeto5 = { value: 'E' };

var listaA = [objeto1, objeto2, objeto3, objeto4, objeto5];
var listaB = [objeto1, objeto2];

listaA = listaA.filter(function (objeto) { 
  return listaB.indexOf(objeto) == -1 
});
console.log(listaA);

But remember that the comparison of objects is done by reference, so even if both objects have exactly the same properties and values, they will still be considered as different.

var objeto1 = { value: 'A' };
var objeto2 = Object.assign({}, objeto1);
console.log(objeto1, objeto2, objeto1 == objeto2);

Optionally, you can compare the objects using the hash of the same.

Array.prototype.except = function(lista) {
  lista = lista.map(function (object) {
    return objectHash.sha1(object);
  });
  return this.filter(function (objeto) { 
    var objHash = objectHash.sha1(objeto)
    return lista.indexOf(objHash) == -1;
  });
}

var listaA = [
  { value: 'A' }, 
  { value: 'B' }, 
  { value: 'C' }, 
  { value: 'D' }, 
  { value: 'E' }
];
var listaB = [
  { value: 'B' }, 
  { value: 'D' }
];
var lista = listaA.except(listaB);
console.log(lista);
<script src="https://rawgit.com/puleos/object-hash/master/dist/object_hash.js"></script>

  • Excellent observation regarding the reference of objects.

  • @Marcioeric edited the answer, an alternative if you need to compare the objects by their value.

2

Another option is to remove the index from the array itself:

var a = [{a: 1}, {b: 1}, {c:1}, {d:1}, {e:1}];
var b = [{b:1}, {e:1}];

a.map(function(item, index){
  JSON.stringify(b).indexOf(JSON.stringify(item)) == -1 ? '' : a.splice(index,1) ;
});

console.log(a);

1

If you want to remove all elements contained in array a of array b, you can use the function filter:

var c = a.filter(function(item) {
  return b.indexOf(item) === -1; // Não foi encontrado
});

The returned elements will be those that obtain a result true, that are not contained in array b.

1

Just make a filter and check with the includes if each item in the array a exists in the array b.

Just remember that objects are always compared by reference, that is, even if the properties of two objects have the same values they are not equal.

var obj1 = { value: 'A' };
var obj2 = { value: 'B' };
var obj3 = { value: 'C' };
var obj4 = { value: 'E' };

var a = [ obj1, obj2, obj3, obj4];
var b = [ obj1, obj2 ];

a = a.filter(function(el) {
  return !b.includes(el);
} );

console.log(a);

1

You can use the native Javascript function splice.

The splice() method changes the contents of a list, adding new elements while removing old elements.

The function receives up to three parameters, but we only need the first two. The first is the index at which you will remove something, and the second parameter is the amount of items you want to remove from that index.

Soon:

var objeto1 = {}, objeto2 = {}, objeto3 = {};
var a = [objeto1, objeto2, objeto3];
var b = [objeto2];

for (var i = a.length - 1; i >= 0; i++) {
    if (b.indexOf(a[i]) > -1) {
        a = a.splice(i, 1);
    }
}

At the end of the above code, the vector a will contain only the objects objeto1 and objeto3.

Note that the comparison between objects in Javascript, used internally by the method indexOf of the vector, it is by reference. This type of comparison works if you add the same objects to the two vectors. If you add different objects, but with similar properties, you will still need to implement a function to search for the objects.

1

You can use this function

  copiarObjeto(original){
    var copia = original instanceof Array ? [] : {};
    for (let i in original) {
      if (original[i] && typeof original[i] == 'object') copia[i] = this.copiarObjeto(original[i]);
      else copia[i] = original[i];
    }
    return copia;
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.