Skip to content

Instantly share code, notes, and snippets.

@ViliamKopecky
Created March 2, 2022 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ViliamKopecky/305a3bca599be7bc737114e7dda1c835 to your computer and use it in GitHub Desktop.
Save ViliamKopecky/305a3bca599be7bc737114e7dda1c835 to your computer and use it in GitHub Desktop.
array of objects to object of arrays
type ArrayifyFields<Original> = Original extends Record<string, unknown>
? {
[key in keyof Original]: Original[key][]
}
: never
export function arrayifyFields<Item extends Record<string, unknown>>(items: Item[]) {
return items.reduce((grouped, item) => {
const entries = Object.entries(item).map(
([key, value]) => [key, grouped ? [grouped[key], value] : [value]] as const,
)
return Object.fromEntries(entries) as ArrayifyFields<Item>
}, null as null | ArrayifyFields<Item>)
}
export function groupByName<Item extends { name: string }>(items: Item[]): Item[][] {
const repo: Record<string, Item[]> = {}
items.forEach(item => {
repo[item.name] = [...(repo[item.name] ?? []), item]
})
return Object.entries(repo).map(([_key, value]) => value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment