Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Created April 13, 2021 21: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 kjbrum/beb9530a36b75cf8a040c2fd9935f7b8 to your computer and use it in GitHub Desktop.
Save kjbrum/beb9530a36b75cf8a040c2fd9935f7b8 to your computer and use it in GitHub Desktop.
Group an array of object by a specified key
/**
* Group an array of object by a specified key
* @param {array} items Array of objects
* @param {string} key Key to use for grouping
* @returns {object}
*/
const groupBy = (items, key) => {
return items.reduce(
(result, item) => ({
...result,
[item[key]]: [...(result[item[key]] || []), item],
}),
{}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment