Skip to content

Instantly share code, notes, and snippets.

@lcherone
Last active June 26, 2020 23:58
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 lcherone/e0b63a3af841330419cbe290ab87ddb3 to your computer and use it in GitHub Desktop.
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
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