Created
May 25, 2023 05:35
-
-
Save wonderbeyond/b05b2715fbd897c7a5b657aaea64c370 to your computer and use it in GitHub Desktop.
[javascript] group by
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
/** | |
* | |
* @param {Object[]} dataset | |
* @param {string} key | |
* @returns {Object.<string, Object[]>} | |
* @example groupBy([ | |
* {scope: 'step:1', name: 'API'}, | |
* {scope: 'step:1', name: 'amount'}, | |
* {scope: 'step:2', name: 'Solvent'} | |
* ], 'scope') => { | |
* 'step:1': [{ scope: 'step:1', name: 'API' }, { scope: 'step:1', name: 'amount' }], | |
* 'step:2': [{ scope: 'step:2', name: 'Solvent' }] | |
* } | |
*/ | |
export default function groupBy(dataset, key) { | |
return dataset.reduce(function (rv, x) { | |
(rv[x[key]] = rv[x[key]] || []).push(x); | |
return rv; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment