Skip to content

Instantly share code, notes, and snippets.

@juliarose
Created April 23, 2019 17:14
Show Gist options
  • Save juliarose/63fad828f12ad634f34b174b9e1f8241 to your computer and use it in GitHub Desktop.
Save juliarose/63fad828f12ad634f34b174b9e1f8241 to your computer and use it in GitHub Desktop.
/**
* Group an array by value from key
* @param {Array} arr - Array
* @param {(String|Function)} key - Key to take value from
* @returns {Object} Object of groups
*/
function groupBy(arr, key) {
// if 'key' is a function, set fn to 'key'
let fn = typeof key === 'function' ? key : null;
return arr.reduce((a, b) => {
let value = fn ? fn(b) : b[key];
(a[value] = a[value] || []).push(b);
return a;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment