I have two arrays, old and new, which hold objects at each position. How would I sync or find the delta (i.e. what is new, updated and deleted from the new array compared to the old array)
var o = [
{id:1, title:"title 1", type:"foo"},
{id:2, title:"title 2", type:"foo"},
{id:3, title:"title 3", type:"foo"}
];
var n = [
{id:1, title:"title 1", type:"foo"},
{id:2, title:"title updated", type:"foo"},
{id:4, title:"title 4", type:"foo"}
];
With the above data, using id as the key, we'd find that item with id=2 has an updated title, item with id=3 is deleted, and item with id=4 is new.
Is there an existing library out there that has useful functions, or is it a case of loop and inner loop, compare each row..e.g.
for(var i=0, l=o.length; i<l; i++)
{
for(var x=0, ln=n.length; x<ln; x++)
{
//compare when o[i].id == n[x].id
}
}
Do this kind of comparison three times, to find new, updated and deleted?
There's no magic to do what you need. You need to iterate through both objects looking for changes. A good suggestion is to turn your structure into maps for faster searches.
/**
* Creates a map out of an array be choosing what property to key by
* @param {object[]} array Array that will be converted into a map
* @param {string} prop Name of property to key by
* @return {object} The mapped array. Example:
* mapFromArray([{a:1,b:2}, {a:3,b:4}], 'a')
* returns {1: {a:1,b:2}, 3: {a:3,b:4}}
*/
function mapFromArray(array, prop) {
var map = {};
for (var i=0; i < array.length; i++) {
map[ array[i][prop] ] = array[i];
}
return map;
}
function isEqual(a, b) {
return a.title === b.title && a.type === b.type;
}
/**
* @param {object[]} o old array of objects
* @param {object[]} n new array of objects
* @param {object} An object with changes
*/
function getDelta(o, n, comparator) {
var delta = {
added: [],
deleted: [],
changed: []
};
var mapO = mapFromArray(o, 'id');
var mapN = mapFromArray(n, 'id');
for (var id in mapO) {
if (!mapN.hasOwnProperty(id)) {
delta.deleted.push(mapO[id]);
} else if (!comparator(mapN[id], mapO[id])){
delta.changed.push(mapN[id]);
}
}
for (var id in mapN) {
if (!mapO.hasOwnProperty(id)) {
delta.added.push( mapN[id] )
}
}
return delta;
}
// Call it like
var delta = getDelta(o,n, isEqual);
See http://jsfiddle.net/wjdZ6/1/ for an example
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