Given:
[{id: '1'},{id: '2'},{id: '3'},{id: '4'},{id: '5'}][{id: '1'},{id: '5'},{id: '6'},{id: '7'},{id: '8'}]How to determine which objects
In this case:
{id: '2'},{id: '3'},{id: '4'} should be removed{id: '6'},{id: '7'},{id: '8'} should be addedPerformance is not extremely important, my dataset is usually around 200.
Edit: I need to know about elements to be added/removed because "current" array correlates to DOM nodes and I don't just want to delete them all and add from scratch - already tried that and performance is far from perfect.
In both cases, this is a classic use case of the set operation "difference". All you need to do is define a difference function, and then apply it with current.difference(new) and new.difference(current).
function difference(a, b, compare) {
let diff = [];
for (let ai = 0; ai < a.length; ai++) {
let exists = false;
for (let bi = 0; bi < b.length; bi++) {
if (compare(a[ai], b[bi])) {
exists = true;
break;
}
}
if (!exists) diff.push(a[ai]);
}
return diff;
}
function getRemoved(oldA, newA) {
return difference(oldA, newA, (a, b) => a.id == b.id);
}
function getAdded(oldA, newA) {
return difference(newA, oldA, (a, b) => a.id == b.id);
}
let current = [{id: '1'}, {id: '2'}, {id: '3'}, {id: '4'}, {id: '5'}];
let newArr = [{id: '1'}, {id: '5'}, {id: '6'}, {id: '7'}, {id: '8'}];
console.log(getRemoved(current, newArr));
console.log(getAdded(current, newArr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With