Skip to content

Instantly share code, notes, and snippets.

@kmylo
Created March 15, 2023 07:07
Show Gist options
  • Save kmylo/ead7121709a14de787b17cba163b351c to your computer and use it in GitHub Desktop.
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)
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;
@kmylo
Copy link
Author

kmylo commented Mar 15, 2023

this is the Array.reduce version:

type ListGroupByMap<T> = Map<T[keyof T], T[]>;

const useListGroupBy = <T>(list: T[], typeKey: keyof T): ListGroupByMap<T> => {
  const updatedListByType = useMemo(() => {
    const listByType = list.reduce((acc: Map<T[keyof T], T[]>, item: T) => {
      const itemValue = item[typeKey];
      const existingList = acc.get(itemValue) ?? [];
      return acc.set(itemValue, [...existingList, item]);
    }, new Map<T[keyof T], T[]>());
    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