I'm using NextJS with Zustand, I have one array of objects in my zustand's state:
[{a:1, b:2}, {a:2, b:3}]
and I have incoming array of objects which have same existing objects + additional unique ones.
[{a:2, b3}, {a:4, b:5}, {a:1, b:2}]
Problem is that the second array that comes in, comes in a different order. Ideally, I'd like append unique items at the end of the previous array. Is looping through the second array with something like say .every() or just a for loop, the fastest way to remove the duplicate items and append new ones? Thanks.
(If it matters, I'm saving these arrays in zustand's state)
for loops and .every() - very resource intensive.
Here is a way to implement the same
let dic1 = [{a:1, b:2}, {a:2, b:3}]
let dic2 = [{a:2, b:3}, {a:4, b:5}, {a:1, b:2}]
// You can use a better hash function. Search online for one
function hash(dict) {
return Object.keys(dict).join("").concat(
Object.values(dict).join(''))
};
let set = new Set(dic1.map(hash));
dic2.forEach(x=>{if(!set.has(hash(x))) dic1.push(x)});
console.log(dic1);