Last active
June 26, 2020 23:58
-
-
Save lcherone/e0b63a3af841330419cbe290ab87ddb3 to your computer and use it in GitHub Desktop.
Javascript merge multiple arrays, de-duped by property name, O(N1) using reduce
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 array1 = [ | |
{ name: 'a', creationDate: new Date() }, | |
{ name: 'b', creationDate: new Date() }, | |
] | |
const array2 = [ | |
{ name: 'a', creationDate: new Date() }, | |
{ name: 'c', creationDate: new Date() }, | |
] | |
const mergeBy = (...arrays) => { | |
const prop_index = arrays.length - 1, key = arrays[prop_index] | |
if (typeof arrays[prop_index] !== 'string') throw Error('Last argument must be a string') | |
arrays.splice(-1, 1) | |
return Object.values( | |
arrays.reduce((acc, cur) => { | |
cur.forEach(prop => acc[prop[key]] = acc[prop[key]] ? Object.assign(acc[prop[key]], prop) : prop) | |
return acc | |
}, {}) | |
) | |
} | |
console.log('--------') | |
console.log(mergeBy(array1, array2, 'name')) | |
console.log('--------') | |
console.log(mergeBy(array1, array2, 'creationDate')) | |
// .etc: | |
// console.log(mergeBy(array1, array2, array3, 'name')) | |
// console.log(mergeBy(array1, array2, array3, array4, 'name')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment