Choose Theme

Array reduce() tricks

· 1 min read · #JavaScript #TypeScript
--

The reduce() method is one of the most powerful array methods in JavaScript. Here are some clever uses:

// Group by property
const groupBy = <T>(arr: T[], key: keyof T) =>
arr.reduce((acc, item) => {
const group = String(item[key]);
return { ...acc, [group]: [...(acc[group] || []), item] };
}, {} as Record<string, T[]>);
// Count occurrences
const countBy = <T>(arr: T[], fn: (item: T) => string) =>
arr.reduce((acc, item) => {
const key = fn(item);
return { ...acc, [key]: (acc[key] || 0) + 1 };
}, {} as Record<string, number>);

These patterns work great with TypeScript for type-safe transformations.