Created
March 2, 2022 08:40
-
-
Save ViliamKopecky/305a3bca599be7bc737114e7dda1c835 to your computer and use it in GitHub Desktop.
array of objects to object of arrays
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
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