You can also try some like this if you want to get all the changes (added, removed, updated and unchanged) along with checking with multiples keys for an object.
Time complexity is O(N) and Space complexity is O(N).
The assumption is "id" is unique.
function getProductChanges(oldProductsList, newProductsList) {
let oldProductsMap = {};
let newProductsMap = {};
let addedProductsList = [];
let updatedProductsList = [];
let removedProductsList = [];
let unchangedProductsList = [];
// considering id is unique
// creating map for old products list
oldProductsList.map((oldProduct) => {
oldProductsMap[oldProduct.id] = oldProduct;
});
// creating map for new products list and
// filtering newly added, updated and unchanged products list
newProductsList.map((newProduct) => {
newProductsMap[newProduct.id] = newProduct;
let oldProduct = oldProductsMap[newProduct.id];
if (oldProduct) {
// if an existing product is updated
if (JSON.stringify(oldProduct) !== JSON.stringify(newProduct)) {
updatedProductsList.push(newProduct);
} else {
unchangedProductsList.push(newProduct);
}
}
else {
// if a new product is added
addedProductsList.push(newProduct);
}
});
// populating removedProductsList
removedProductsList = oldProductsList.filter((oldProduct) => !newProductsMap[oldProduct.id]);
return {
added: addedProductsList,
updated: updatedProductsList,
removed: removedProductsList,
unchanged: unchangedProductsList,
};
}
Input:
let products = [
{ id: "A32S", title: "Car" },
{ id: "D12E", title: "Rabbit" },
{ id: "A321", title: "Ghost" },
{ id: "A320", title: "Lion" },
];
let newProducts = [
{ id: "A32S", title: "Ferrari" },
{ id: "D12E", title: "Rabbit" },
{ id: "A321", title: "Ghost" },
{ id: "A322", title: "Zebra" },
];
console.log(getProductChanges(products, newProducts));
Output:
{
added: [{ id: "A322", title: "Zebra" }],
removed: [{ id: "A320", title: "Lion" }],
unchanged: [
{ id: "D12E", title: "Rabbit" },
{ id: "A321", title: "Ghost" },
],
updated: [{ id: "A32S", title: "Ferrari" }],
}