假设我们有这个
oldArray = [
{ id: 1, position: 'DEV OM'},
{ id: 2, position: 'Senior Developer'},
]
newArray = [
{ id: 2, position: 'Senior Developer'},
{ id: 3, position: 'Junior Developer'},
]
现在我们如何才能在这些数组中获取已删除和添加的项目?
addedItems = getAddedItems(oldArray, newArray)
removedItems = getRemovedItems(oldArray, newArray)
// Output for addedItems
[
{ id: 3, position: 'Junior Developer'}
]
// Output for removedItems
[
{ id: 1, position: 'DEV OM'}
]
我正在使用typescript / angular2 app
答案 0 :(得分:2)
您需要的是找到2个数组之间差异的函数:
let oldArray = [
{ id: 1, position: 'DEV OM'},
{ id: 2, position: 'Senior Developer'}
]
let newArray = [
{ id: 2, position: 'Senior Developer'},
{ id: 3, position: 'Junior Developer'}
]
function difference(a,b) {
return a.filter(itema => !b.some(itemb => itemb.id===itema.id));
}
console.log(difference(oldArray,newArray))
console.log(difference(newArray,oldArray))