Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Last active August 30, 2018 21:08
Show Gist options
  • Save NinoScript/25899e4dd0827cfb2b0fffb4e6c7bb38 to your computer and use it in GitHub Desktop.
Save NinoScript/25899e4dd0827cfb2b0fffb4e6c7bb38 to your computer and use it in GitHub Desktop.
export function groupBy<T, K>(array: T[], getKey: (value: T) => K): Map<K, T[]> {
return array.reduce(
(groups, item) => {
const key = getKey(item);
const innerArray = groups.get(key);
if (innerArray === undefined) {
groups.set(key, [item])
} else {
innerArray.push(item)
}
return groups
},
new Map<K, T[]>()
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment