Skip to content

Instantly share code, notes, and snippets.

@danielcardeenas
Last active August 3, 2021 03:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielcardeenas/b2cd546b2fd4917ecd17d0c855a1d0fd to your computer and use it in GitHub Desktop.
Save danielcardeenas/b2cd546b2fd4917ecd17d0c855a1d0fd to your computer and use it in GitHub Desktop.
Group array of objects by property (Typed)
/**
* Groups array by given key
* @param items
* @param fn
* @returns
*/
function groupBy<T, K extends string | number>(
items: T[],
fn: (item: T) => K,
): { [key: string]: T[] } {
return items.reduce(
(result, item) => ({
...result,
[fn(item)]: [...(result[fn(item).toString()] || []), item],
}),
{},
);
}
// Example usage
// ==========================
const plants = [
{
name: 'Velour',
type: 'Cactus'
},
{
name: 'Sunburst',
type: 'Cactus'
},
{
name: 'Chamomile',
type: 'Herb'
}
];
const grouped = groupBy(plants, (plant) => plant.type);
console.log(grouped);
/*
{
Cactus: [
{
name: 'Velour',
type: 'Cactus'
},
{
name: 'Sunburst',
type: 'Cactus'
},
],
Herb: [
{
name: 'Chamomile',
type: 'Herb'
},
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment