您可以找到添加和删除的项目,如下所示:
var origArray = [...]; // assume first set of data is in origArray
var newArray = [...]; // second set of data is in newArray
function makeMap(array, key) {
var map = {};
for (var i = 0; i < array.length; i++) {
map[array[i][key]] = true;
}
return(map);
}
function compareArrayToMap(array, map) {
var item, var results = [];
for (var i = 0; i < array.length; i++) {
item = array[i];
if (!(item.id in map)) {
results.push(item);
}
}
return(results);
}
// build id map for each array
var origMap = makeMap(origArray, "id");
var newMap = makeMap(newArray, "id");
// find items that have been removed
var removedItems = compareArrayToMap(origArray, newMap);
// find items that have been added
var addedItems = compareArrayToMap(newArray, origMap);