0

Is there a simple way to achieve this.

I have 2 array of objects (old and new items) and I need to identify what all items were added, removed and unchanged based on a property in the object and respectively push the object in the desired array of the overview variable object.

const compareGroups = (oldG, newG) => {
  const overview = { added: [], removed: [], unchanged: [] };
  const seen = [];
  let newItem = null;
  let found = false;
  for (const i in newG) {
    if (newG[i]) {
      newItem = newG[i];
      found = false;
      for (const j in oldG) {
        if (oldG[j]) {
          if (oldG[j].email === newItem.email) {
            overview.unchanged.push(newItem);
            seen.push(newItem.email);
            found = true;
            break;
          }
        }
      }
      if (!found) {
        seen.push(newItem.email);
        overview.added.push(newItem);
      }
    }
  }
  for (const k in oldG) {
    if (oldG[k]) {
      if (!seen.includes(oldG[k].email)) {
        overview.removed.push(oldG[k]);
      }
    }
  }
  return overview;
}


const oldG = [{email: 'a'}, {email:'b'}, {email:'c'}];
const newG = [{email: 'a'}, {email:'d'}, {email:'e'}];
console.log(compareGroups(oldG, newG));

Expected output:

{
  "added": [{"email": "d"},{"email": "e"}],
  "removed": [{"email": "b"},{"email": "c"}],
  "unchanged": [{"email": "a"}]
}
joyBlanks
  • 6,419
  • 1
  • 22
  • 47
  • @VLAZ actually no it gives all different elements other than the unchanged ones, so basically provides me disjunction, actually I need intersection and disjunction – joyBlanks Mar 15 '20 at 22:35
  • You can have a look [here](https://stackoverflow.com/a/33034768/) - that shows simple operations but it's not as performant as the other question. Still, it can easily be adapted using the same fashion of set operations. – VLAZ Mar 15 '20 at 22:51
  • yes I had few elements went with this one finally. Thanks – joyBlanks Mar 15 '20 at 23:30

0 Answers0