如何快速对比2个数组数据？

``````[{
"id": "id1",
"name": "name1"
}, {
"id": "id2",
"name": "name2"
}]``````

``````let oldList = [
{"id": "id1", "name": "name1"},
{"id": "id2", "name": "name2"}
];

let newList = [
{"id": "id1", "name": "name4"},
{"id": "id3", "name": "name3"}
];

// getDiffData为方案所需实现的算法
let {addList, removeList, changeList} = getDiffData(oldList, newList, 'id');

// [{"id": "id3", "name": "name3"}]

console.log(removeList);
// [{"id": "id2", "name": "name2"}]

console.log(changeList);
// [{"id": "id1", "name": "name4"}] or [{"id": "id1", "name": "name1"}]``````

2 个回答
``````function getDiffData(oldList, newList) {
const oldData = oldList.reduce((data, item) => {
data[item.id] = item;
return data;
}, {});
const changeList = [];

for (const item of newList) {
if (!oldData[item.id]) {
} else {
if (oldData[item.id].name !== item.name) {
changeList.push(item);
}
oldData[item.id] = true;
}
}

const removeList = oldList.filter(item => oldData[item.id] !== true);

return {
changeList,
removeList,
};
}``````

``````const oldList = Array.from({length: 300000}, (v, id) => ({
id,
name: (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1),
}));
const newList = Array.from({length: 350000}, (v, id) => ({
id,
name: (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1),
}));

console.time('getDiffData');
const {addList, changeList, removeList} = getDiffData(oldList, newList);
console.timeEnd('getDiffData');