Last active
October 10, 2019 15:48
-
-
Save jbreckmckye/09d7266d40e99271ab9562bf597115fd to your computer and use it in GitHub Desktop.
Group objects by a string field
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
function group (rows, discriminant) { | |
const asMap = rows.reduce( | |
(acc, item) => { | |
const key = item[discriminant] | |
return { | |
...acc, | |
[key]: acc[key] ? [...acc[key], item] : [item] | |
} | |
}, | |
{} | |
) | |
const asArray = Object.keys(asMap).reduce( | |
(acc, key) => [ | |
...acc, | |
[...asMap[key]] | |
], | |
[] | |
) | |
return { | |
asMap, | |
asArray | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment