I try to find the most effective way to compare two arrays of objects and return filtered difference in JavaScript.
I build an app to update stock in DB. But this app can use many users in the same time. I would like to avoid calling API and refresh all data in app each time changes are made, bcz database is too big and loading time is long. I have and old data locally, with help of MQTT I receive new data the moment its updated by someone. The goal is to find the difference between two objects and update locally only the one that has changes. Objects looks like this:
let oldData = [
{ artnr: 12, affiliateid: 1, stock: 10 },
{ artnr: 12, affiliateid: 2, stock: 15 },
{ artnr: 12, affiliateid: 3, stock: 1 },
{ artnr: 13, affiliateid: 2, stock: 2 }
]
let newData = [
{ artnr: 12, affiliateid: 1, stock: 11 },
{ artnr: 12, affiliateid: 2, stock: 20 },
{ artnr: 12, affiliateid: 3, stock: 1 },
{ artnr: 13, affiliateid: 2, stock: 2 }
]
The only way I can think about it’s foreach. But in real life each of arrays will contain thousands of objects, so I would like to avoid iterations type of: (my working func)
let oldData = [
{ artnr: 12, affiliateid: 1, stock: 10 },
{ artnr: 12, affiliateid: 2, stock: 1 },
{ artnr: 13, affiliateid: 2, stock: 2 }
]
let newData = [
{ artnr: 12, affiliateid: 1, stock: 11 },
{ artnr: 12, affiliateid: 2, stock: 1 },
{ artnr: 13, affiliateid: 2, stock: 2 }
]
const filterObjDiff = () => {
var obj1 = oldData as StockUpdate.stockMqttResponse[]
var obj2 = newData as StockUpdate.stockMqttResponse[]
obj1.forEach(oldD => {
obj2.forEach(newD => {
if (
oldD.affiliateid == newD.affiliateid &&
oldD.artnr == newD.artnr &&
oldD.stock != newD.stock
) {
console.log('diff', newD)
}
})
})
}
Is there an effective way to white func
const FilterObjectDiff = (oldData, newData) => {
// filter here without iterations
return [
{ artnr: 12, affiliateid: 1, stock: 11 },
{ artnr: 12, affiliateid: 2, stock: 20 }
]
}
I would appreciate any ideas.
3
Answers
I think the easiest way to improve the performance is with Hash Map since it’s O(1) of finding the specific value with a key. I’ve refactored it with Hash Map and it’s equivalent.
Two approaches:
artnr
andaffiliateid
, mapping the old and the new data by that unique id and compare the values in that hashmapoldData
andnewData
in a similar way, then using two indices to iterate over both arrays at the same time. Using the same sort function to determine which index is behind the other.This minimizes the comparisons between the two arrays and doesn’t require the memory of a hashmap.
You could create a
Map
fromoldData
using a combination ofaffiliateid
andartnr
as the key, and then iteratenewData
in yourFilterObjectDiff
function, checkingaffiliateid
/artnr
combination exists inoldData
; andIf neither of these cases are true, then the
newData
needs to update the DB.We use a
Map
as lookup time isO(1)
and thus the lookup time for all ofnewData
isO(n)
wheren
is the length ofnewData
.