Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Created March 25, 2021 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiro-hiro/81dc1b42afccadcc2d677f17aea5cca0 to your computer and use it in GitHub Desktop.
Save chiro-hiro/81dc1b42afccadcc2d677f17aea5cca0 to your computer and use it in GitHub Desktop.
Merge array by unique key
const src = [
{ name: 'a', value: 1 },
{ name: 'b', value: 2 },
{ name: 'c', value: 3 },
];
const dst = [
{ name: 'd', value: 4 },
{ name: 'a', value: 5 },
{ name: 'f', value: 6 },
];
const reducer = (previous: any, current: any, index: number) => {
if (index === 1) {
return {
[previous.name]: previous,
[current.name]: current,
};
}
return {
...previous,
[current.name]: current,
};
};
const r1 = dst.reduce(reducer);
const r2 = src.reduce(reducer);
console.log(Object.values({ ...r1, ...r2 }));
/*
[ { name: 'd', value: 4 },
{ name: 'a', value: 1 },
{ name: 'f', value: 6 },
{ name: 'b', value: 2 },
{ name: 'c', value: 3 } ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment