Skip to content

Instantly share code, notes, and snippets.

@Slackwise
Created June 9, 2019 18:44
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 Slackwise/6a47985e8212a584799db0863385bf87 to your computer and use it in GitHub Desktop.
Save Slackwise/6a47985e8212a584799db0863385bf87 to your computer and use it in GitHub Desktop.
Minimal implementation of an Array groupBy function.
// As a function:
const groupBy = (array, key) =>
array.reduce((a, c) => (
{
...a,
[c[key]]: [ ...a[c[key]] || [], c ]
}
), {});
// As a method:
Array.prototype.groupBy = function(key) {
return this.reduce((a, c) => (
{
...a,
[c[key]]: [ ...a[c[key]] || [], c ]
}
), {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment