2017-07-26 55 views
-1

認爲我們有這個TS - 如何從舊陣列和新陣列中獲取陣列中已刪除和添加的項目?

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'} 
] 

進出口使用打字稿/ angular2應用

+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))

+0

不錯..不知道過濾器/一些。正在看lodash。你也應該改變 - 只是爲了好玩!當位置更改爲ID! – JGFMK