Finding netchange (inserts, deletes, updates) from two javascript arrays

Views: 160   

Its a very common usecase to find netchange when you are updating documents. The following code shows you how simply you can calculate the netchange in JavaScript when you have given with old array of ids & new array of ids.

let oldData = [1, 3, 5, 6, 7, 8, 9];
let newData = [2, 3, 4, 5, 6, 7];

let inserts = newData.filter(ele => !oldData.includes(ele));
let deletes = oldData.filter(ele => !newData.includes(ele));
let updates = newData.filter(ele => oldData.includes(ele));



console.log('inserts:', inserts);
console.log('deletes:', deletes);
console.log('updates:', updates);

Output

inserts: [ 2, 4 ]
deletes: [ 1, 8, 9 ]
updates: [ 3, 5, 6, 7 ]
On By