groupByKey
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.
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.
import { groupByKey } from "@/utils/groupByKey";
const grouped = groupByKey(arr, "key");
// biome-ignore lint/suspicious/noExplicitAny: we need to use any to allow for any grouped values
export function groupByKey<T extends Record<string, any>>(
arr: T[],
key: keyof T,
): Record<string, T[]> {
return arr.reduce(
(acc, item) => {
const groupKey = String(item[key]); // Ensure the key is a string
if (!acc[groupKey]) {
acc[groupKey] = [];
}
acc[groupKey].push(item);
return acc;
},
{} as Record<string, T[]>,
);
}