Javascript merge multiple arrays, de-duped by property name, O(N1) using reduce
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