a utility function for grouping an array of objects by a key.
soon we can just use javascript object group by method but until then this method is useful.right now its on newly available in the latest version of javascript.
export function groupByKey<T extends Record<string, unknown>>(
arr: T[],
key: keyof T,
): Record<string, T[]> {
return arr.reduce(
(acc, item) => {
const groupKey = String(item[key]);
if (!acc[groupKey]) acc[groupKey] = [];
acc[groupKey].push(item);
return acc;
},
{} as Record<string, T[]>,
);
}
Installation
Usage
import { groupByKey } from "@/utils/groupByKey";
const grouped = groupByKey(arr, "key");