Compare two array of objects to find distinct values by all key values
So I found a lot of documentation like Get unique values by comparing old and new array objects but my case is a bit more complex.
In my case I want to compare two databases of prices, every week, finding out which prices have changed and then add only them to the existing database. I give you an example:
oldPrices = [{"date": "07-07-2022", "price": 129, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 2 }]
newPrices = [{"date": "07-07-2022", "price": 139, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 1 }, {"date": "08-07-2022", "price": 139, "locationId": 2 }]
Expected output to add to oldPrices:
[{"date": "07-07-2022", "price": 139, "locationId": 1 }]
What I have tried so far:
var data1 = {{(table17.data)}};
var data2 = {{ formatDataAsArray(table18.data) }};
const oldPrices = data1.map (({date, price, locationId}) => ({date, price, locationId}));
const newPrices = data2.map (({date, price, locationId}) => ({date, price, locationId}));
function getDifference(array1, array2) {
return array1.filter(object1 => {
return !array2.some(object2 => {
return object1.price === object2.price;
});
});
}
const difference = [
...getDifference(oldPrices, newPrices),
...getDifference(newPrices, oldPrices)
];
console.log(difference)
Outcome = empty
There is only outcome, if the newPrice data contains prices, that were not included in the oldPrices data. This makes no sense, since I want to add all the objects containing combinations of the 3 keys, that are new (unique).
What I need is the function not only check the price of every object, but the combination of date, price and locationId, so that the output in this case would again be [{"date": "07-07-2022", "price": 139, "locationId": 1 }].
I think this is good solution for your problem
const oldPrices = [
{ date: "07-07-2022", price: 129, locationId: 1 },
{ date: "08-07-2022", price: 139, locationId: 1 },
{ date: "08-07-2022", price: 139, locationId: 2 },
];
const newPrices = [
{ date: "07-07-2022", price: 139, locationId: 1 },
{ date: "08-07-2022", price: 139, locationId: 1 },
{ date: "08-07-2022", price: 139, locationId: 2 },
];
let old = oldPrices.map((p) => JSON.stringify(p));
let unique = newPrices.filter((p) => !old.includes(JSON.stringify(p)));
console.log(unique);