1

I have two objects:

Object One

[
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

Object Two

[
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

I would like to compare both arrays and remove the duplicate objects from the second array so my output looks like:

[
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 }
]

I have tried to use ES6 to do this by running this:

  const result = objectTwo.filter((obj) => {
    return !objectOne.includes(obj);
  });

However, result is coming out as:

[
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

Could someone please guide me on where I am going wrong and what the most optimal way of achieving this would be? In real life, both arrays have are 10000+ objects.

I am not testing equality as both arrays are not the same, I am more testing how to remove duplicates.

Thanks :)

user3180997
  • 1,836
  • 3
  • 19
  • 31

1 Answers1

3

Try this code:

obj1 = [
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

obj2 = [
  { repo: 'edat-ims-github', status: 200 },
  { repo: 'edat-ims-github-spa', status: 200 },
  { repo: 'test-repo-one', status: 200 },
  { repo: 'test-repo-two', status: 200 },
  { repo: 'test-repo-three', status: 200 }
]

filteredArr = obj2.filter(el1 => {
  return obj1.every(el2 => {
    return !(el1.repo == el2.repo && el1.status == el2.status)
  })
})

console.log(filteredArr)

It starts off with checking if every element satisfies that el1 is NOT in el2. If it is in el2, then the return statement inside the every returns a false, which causes the function to break off and return false. This means that it is removed from the filtered array filteredArr. However, if it is not in el2, then the every statement returns true, which means that it is included in the filteredArr.

Endothermic_Dragon
  • 1,147
  • 3
  • 13