Skip to content

Instantly share code, notes, and snippets.

@MatteoGioioso
Last active August 2, 2019 02:30
Show Gist options
  • Save MatteoGioioso/7a9d0327e068f363d95aae4a3aaee6ec to your computer and use it in GitHub Desktop.
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
/**
* 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