Created
March 25, 2021 14:22
-
-
Save chiro-hiro/81dc1b42afccadcc2d677f17aea5cca0 to your computer and use it in GitHub Desktop.
Merge array by unique key
This file contains 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 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