Created
April 23, 2019 17:14
-
-
Save juliarose/63fad828f12ad634f34b174b9e1f8241 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
/** | |
* 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