Created
February 16, 2018 12:41
-
-
Save savelichalex/d78f20d96ec4cfe56de6c1c25348e00e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arraysDiff = (first, second, key) => { | |
const keysInFirst = first.reduce((acc, item) => { | |
const id = item[key]; | |
acc[id] = item; | |
return acc; | |
}, {}); | |
const { common, added } = second.reduce( | |
(acc, item) => { | |
const id = item[key]; | |
const isExist = keysInFirst[id]; | |
if (isExist) { | |
keysInFirst[id] = null; | |
acc.common.push(item); | |
} else { | |
acc.added.push(item); | |
} | |
return acc; | |
}, | |
{ common: [], added: [] } | |
); | |
const removed = Object.keys(keysInFirst).reduce((acc, key) => { | |
const item = keysInFirst[key]; | |
if (item == null) { | |
return acc; | |
} | |
acc.push(item); | |
return acc; | |
}, []); | |
return { | |
removed, | |
common, | |
added, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment