Last active
May 25, 2023 19:30
-
-
Save tolotrasmile/5f7e5842ba32bebe34a3f805c984264c to your computer and use it in GitHub Desktop.
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
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