Created
March 15, 2023 07:07
-
-
Save kmylo/ead7121709a14de787b17cba163b351c to your computer and use it in GitHub Desktop.
react custom hook to group by some key array of items (Map version)
This file contains hidden or 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
import { useMemo } from "react"; | |
type ListGroupByMap<T> = Map<T[keyof T], T[]>; | |
const useListGroupBy = <T,>(list: T[], typeKey: keyof T): ListGroupByMap<T> => { | |
const updatedListByType = useMemo(() => { | |
const listByType = new Map<T[keyof T], T[]>(); | |
list.forEach((item) => { | |
const itemValue = item[typeKey]; | |
if (listByType.has(itemValue)) { | |
listByType.get(itemValue)?.push(item); | |
} else { | |
listByType.set(itemValue, [item]); | |
} | |
}); | |
return listByType; | |
}, [list, typeKey]); | |
return updatedListByType; | |
}; | |
export default useListGroupBy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is the Array.reduce version: