Skip to content

Instantly share code, notes, and snippets.

@savelichalex
Created February 16, 2018 12:41
Show Gist options
  • Save savelichalex/d78f20d96ec4cfe56de6c1c25348e00e to your computer and use it in GitHub Desktop.
Save savelichalex/d78f20d96ec4cfe56de6c1c25348e00e to your computer and use it in GitHub Desktop.
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