Last active
May 27, 2021 11:41
-
-
Save masonlouchart/da141b3af477ff04ccc626f188110f28 to your computer and use it in GitHub Desktop.
TypeScript groupBy
This file contains hidden or 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
/** | |
* StackOverflow Question = https://stackoverflow.com/questions/14446511 | |
* Based on StackOverflow Anser = https://stackoverflow.com/a/66987261/1832572 | |
*/ | |
/** | |
* Groups items on given criteria. The criteria can be a property or a function | |
* which is applied on each item. | |
* | |
* @param list The elements to be grouped ona criteria | |
* @param groupOn The criteria to group the elements together. Can bee a property | |
* or a function applied on each items. | |
* @return a map of items group on the given criteria. | |
*/ | |
export function groupBy<T, K extends keyof T>(list: T[], groupOn: K | ((i: T) => any)): Map<any, T[]> { | |
const groupFn = typeof groupOn === "function" ? groupOn : (o: T) => o[groupOn]; | |
return list.reduce((map, elm) => { | |
const key = groupFn(elm); | |
let group = map.get(key); | |
if (!group) { | |
group = []; | |
map.set(key, group); | |
} | |
group.push(elm); | |
return map; | |
}, new Map<any, T[]>()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment