Skip to content

Instantly share code, notes, and snippets.

@sungjk
Created July 25, 2018 06:43
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 sungjk/f1f430f13d7e5a5833b2a408fce768ff to your computer and use it in GitHub Desktop.
Save sungjk/f1f430f13d7e5a5833b2a408fce768ff to your computer and use it in GitHub Desktop.
groupBy for javascript
function groupBy(xs, key) {
return xs.reduce(function (rv, x) {
let v = key instanceof Function ? key(x) : x[key];
let el = rv.find((r) => r && r.key === v);
if (el) {
el.values.push(x);
} else {
rv.push({
key: v,
values: [x]
});
}
return rv;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment