Last active
August 2, 2019 02:30
-
-
Save MatteoGioioso/7a9d0327e068f363d95aae4a3aaee6ec to your computer and use it in GitHub Desktop.
How to group an array by key in javascript in a functional style
This file contains hidden or 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
/** | |
* groupArrayByKey | |
* @param array | |
* @param {function(object):number | string} keyExtractorCallback - function to calculate the key | |
* @returns {*} | |
*/ | |
export const groupArrayByKey = (array, keyExtractorCallback) => | |
array.reduce((accumulator, item) => { | |
const key = keyExtractorCallback(item); | |
accumulator[key] = (accumulator[key] || []).concat(item); | |
return accumulator; | |
}, {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment