Last active
December 10, 2018 13:54
-
-
Save rolandcoops/0da6b8bb19793e65f2d2d5d89b65abc4 to your computer and use it in GitHub Desktop.
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
// 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