Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Created May 25, 2023 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wonderbeyond/b05b2715fbd897c7a5b657aaea64c370 to your computer and use it in GitHub Desktop.
Save wonderbeyond/b05b2715fbd897c7a5b657aaea64c370 to your computer and use it in GitHub Desktop.
[javascript] group by
/**
*
* @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