Would you like to create a listview with an items-source and update the view when the items-source changes? For this you need to know what items need to be inserted and deleted. This example shows you how to create an insert and delete list that contains the difference between the old and new items-source.

How do I calculate the difference between two lists in Javascript?

Consider these two lists:

let oldItems = [   1, 2, 3, 4   ];
let newItems = [0, 1, 2,       5];

Moving from oldItems to newItems, you see that:

Here is the code that uses filter and some to calculate the inserts and deletes in Javascript:

let inserts = newItems.filter(x => !oldItems.some(y => x === y));
let deletes = oldItems.filter(x => !newItems.some(y => x === y));

console.log(inserts);
console.log(deletes);

result:

[ 0, 5 ]
[ 3, 4 ]

Object equality

If you want to create inserts and deletes for lists that contain more complex objects like class instances, you might want to consider replacing === with an equals function

Written by Loek van den Ouweland on 2019-02-27.
Questions regarding this artice? You can send them to the address below.