Skip to content

Instantly share code, notes, and snippets.

@tolotrasmile
Last active May 25, 2023 19:30
Show Gist options
  • Save tolotrasmile/5f7e5842ba32bebe34a3f805c984264c to your computer and use it in GitHub Desktop.
Save tolotrasmile/5f7e5842ba32bebe34a3f805c984264c to your computer and use it in GitHub Desktop.
function groupBy<T extends Record<string, unknown>, K extends keyof T>(array: T[], key: K): Record<T[K] & PropertyKey, T[]> {
return array.reduce((result, current) => {
const currentKey = current[key] as T[K] & PropertyKey
if (Array.isArray(result[currentKey])) {
result[currentKey].push(current)
} else {
result[currentKey] = [current]
}
return result
}, {} as Record<T[K] & PropertyKey, T[]>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment