0

I have an array of objects list.data that contains about 2000 objects. I have other array docs that has one object that already exists in the list.data array. I would like to find duplicate/duplicates and remove them from the docs array. The object is a duplicate if it has same values saved in three properties (name, quizmaster, file). Otherwise it is not duplicate. So far I have tried this code:

const filtered = docs.filter(doc => list.data.some(el => doc.name !== el.name && doc.quizmaster !== el.quizmaster && doc.file !== el.file));

Any suggestions what am I doing wrong?

Thank you in advance

AdamSulc
  • 330
  • 2
  • 4
  • 19
  • Does [this question](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) fix your problem? – Toasty Apr 20 '21 at 11:58
  • @Toasty No, I want to find the duplicates based on two arrays, not find duplicates in one array of objects – AdamSulc Apr 20 '21 at 12:02

2 Answers2

1

The conditions should be the other way around:

docs.filter(doc => !list.data.some(el =>
    doc.name === el.name 
    && doc.quizmaster === el.quizmaster 
    && doc.file === el.file));

or

docs.filter(doc => list.data.every(el =>
    doc.name !== el.name 
    || doc.quizmaster !== el.quizmaster 
    || doc.file !== el.file));

If you're doing this multiple times in a hot loop, consider creating a compound key from these properties (e.g. el.name + '/' + el.quizmaster...) and maintain a Set of keys, in which case you can get rid of the inner filter.

georg
  • 211,518
  • 52
  • 313
  • 390
0

This should do the job:

array1 = array1.filter(function(val) {
  return array2.indexOf(val) == -1;
});

or if you like it shorter:

array1 = array1.filter(val => !array2.includes(val));

References

Toasty
  • 1,850
  • 1
  • 6
  • 21