Last active
August 1, 2016 05:40
-
-
Save pisceanfoot/864de63396588be567a37263989bc7d0 to your computer and use it in GitHub Desktop.
get delta data between to array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
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; | |
} | |
var o = [{ | |
id: 1, | |
title: 'A' | |
},{ | |
id: 2, | |
title: 'B' | |
},{ | |
id: 3, | |
title: 'C' | |
}]; | |
var n = [{ | |
id: 2, | |
title: 'A' | |
},{ | |
id: 3, | |
title: 'C' | |
},{ | |
id: 4, | |
title: 'D' | |
}]; | |
console.log(JSON.stringify(getDelta(o,n, isEqual))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
result:
{"added":[{"id":4,"title":"D"}],"deleted":[{"id":1,"title":"A"}],"changed":[{"id":2,"title":"A"}]}