Last active
August 3, 2021 03:37
-
-
Save danielcardeenas/b2cd546b2fd4917ecd17d0c855a1d0fd to your computer and use it in GitHub Desktop.
Group array of objects by property (Typed)
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
/** | |
* 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