rotem-horovitz
    _hello_about-me_blog_snippets_projects_games
find me in:
privacy
← Back to snippets

group-by

Bucket an array of objects into a record keyed by one of their fields. The functional alternative to a manual reduce.

May 20, 2026
utilityarrays

groupBy walks an array once and bins each item under the string form of item[key]. Useful for building lookup tables, rendering grouped lists, or reducing flat data to a categorized shape.

export function groupBy<T>(arr: T[], key: keyof T): Record<string, T[]> {
	return arr.reduce<Record<string, T[]>>((acc, item) => {
		const group = String(item[key]);
		if (!acc[group]) acc[group] = [];
		acc[group].push(item);
		return acc;
	}, {});
}

Notes

  • The key value is coerced via String(...) so numeric and boolean fields work, but at the cost of losing their original type as a record key.
  • For the standard-library equivalent on modern runtimes, see Object.groupBy (ES2024).