Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Last active October 10, 2019 15:48
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 jbreckmckye/09d7266d40e99271ab9562bf597115fd to your computer and use it in GitHub Desktop.
Save jbreckmckye/09d7266d40e99271ab9562bf597115fd to your computer and use it in GitHub Desktop.
Group objects by a string field
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