Created
June 9, 2019 18:44
-
-
Save Slackwise/6a47985e8212a584799db0863385bf87 to your computer and use it in GitHub Desktop.
Minimal implementation of an Array groupBy function.
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
// 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