Created
May 11, 2023 17:06
-
-
Save sagarpanchal/b75c101fbe430e3901aaa222333714fa 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
export function mapListByProp<T extends object, K extends keyof T>(list: T[], key: K) { | |
const output = new Map<T[K], T[]>() | |
for (const item of list) { | |
if (!(key in item)) continue | |
const existingList = (output.has(item[key]) && output.get(item[key])) || [] | |
const updatedList = [...existingList, item] | |
output.set(item[key], updatedList) | |
} | |
return output | |
} | |
export function mapToObject<K extends PropertyKey, V>(map: Map<K, V>) { | |
const mapKeys = map.keys() | |
const output = {} as Record<K, V> | |
for (const key of mapKeys) { | |
output[key] = map.get(key) as V | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use: