Skip to content

Instantly share code, notes, and snippets.

@rolandcoops
Last active December 10, 2018 13:54
Show Gist options
  • Save rolandcoops/0da6b8bb19793e65f2d2d5d89b65abc4 to your computer and use it in GitHub Desktop.
Save rolandcoops/0da6b8bb19793e65f2d2d5d89b65abc4 to your computer and use it in GitHub Desktop.
// quick idea to reduce an array by automatically merging result of iteratee(current, i, src) onto acc
const reduceMerge = (arr, iteratee) =>
arr.reduce((acc, cur, i, src) => {
const val = iteratee(cur, i, src)
// allow falsy returns to result in noop for this iteration
if (!val) {
return acc
} else if (val.constructor === Object) {
return Object.assign(acc, val)
}
throw new TypeError(`Cannot reduce and merge non-object value: ${val}`)
}, {})
const sampleData = [
{ id: 654, firstName: 'John', lastName: 'Doe' },
{ id: 41321, firstName: 'Alias', lastName: 'Pseudonym' },
]
reduceMerge(sampleData, ({ id, firstName, lastName }) => ({
[id]: `${firstName} ${lastName}`,
}))
// --> {654: "John Doe", 41321: "Alias Pseudonym"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment