Last active
July 2, 2021 07:04
-
-
Save khannurien/d25992937fc10dfac843b1a4897eefcb to your computer and use it in GitHub Desktop.
Merge two arrays while ignoring duplicates in the second array based on a predicate.
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
interface MyObject { | |
key: number; | |
value: string; | |
} | |
const array1: MyObject[] = [ | |
{ | |
key: 1, | |
value: 'one' | |
}, | |
{ | |
key: 2, | |
value: 'two' | |
}, | |
{ | |
key: 3, | |
value: 'three' | |
}, | |
{ | |
key: 5, | |
value: 'five' | |
}, | |
]; | |
const array2: MyObject[] = [ | |
{ | |
key: 0, | |
value: 'zero' | |
}, | |
{ | |
key: 2, | |
value: 'NOPE' | |
}, | |
{ | |
key: 4, | |
value: 'four' | |
}, | |
]; | |
const concatenateArrays = (array1: MyObject[], array2: MyObject[]): MyObject[] => { | |
if (!array2 || array2.length === 0) return [...array1]; | |
return array1 | |
.concat(array2) | |
.filter(function(object: MyObject) { | |
return (<Set<number>> this).has(object.key) | |
? false | |
: (<Set<number>> this).add(object.key); | |
}, new Set<number>()); | |
} | |
const array3 = concatenateArrays(array1, array2); | |
console.log(array3); | |
/* | |
[ | |
{ key: 1, value: 'one' }, | |
{ key: 2, value: 'two' }, | |
{ key: 3, value: 'three' }, | |
{ key: 5, value: 'five' }, | |
{ key: 0, value: 'zero' }, | |
{ key: 4, value: 'four' } | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment