Last active
January 24, 2022 21:24
-
-
Save onosendi/509e387003b59d2f3fdfba75c3dfd2da to your computer and use it in GitHub Desktop.
`groupBy` function
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
| const o = [ | |
| { name: 'Bobby', group: 1 }, | |
| { name: 'Jimmy', group: 2 }, | |
| { name: 'Tommy', group: 1 }, | |
| ]; | |
| function groupBy(arr, key = 'group') { | |
| const map = arr.reduce((acc, curr) => ({ | |
| ...acc, | |
| [curr[key]]: [...(acc[curr[key]] || []), curr], | |
| }), {}); | |
| return Object.values(map); | |
| } | |
| const z = groupBy(o); | |
| console.log(z); | |
| // [ | |
| // [ { name: 'Bobby', group: 1 }, { name: 'Tommy', group: 1 } ], | |
| // [ { name: 'Jimmy', group: 2 } ] | |
| // ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment