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"}]
}