Shift N' Tab Shift N' Tab - 3 years ago 105
TypeScript Question

TS - How to get the removed and added items in an array from old and new array?

Supposed we have this

oldArray = [
{ id: 1, position: 'DEV OM'},
{ id: 2, position: 'Senior Developer'},
]

newArray = [
{ id: 2, position: 'Senior Developer'},
{ id: 3, position: 'Junior Developer'},
]


Now how can we get the removed and added items in those arrays?

addedItems = getAddedItems(oldArray, newArray)
removedItems = getRemovedItems(oldArray, newArray)


// Output for addedItems
[
{ id: 3, position: 'Junior Developer'}
]

// Output for removedItems
[
{ id: 1, position: 'DEV OM'}
]


Im using typescript/angular2 app

Answer Source

What you need is a function to find the difference between 2 arrays:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download