Array reduce() tricks
--
The reduce() method is one of the most powerful array methods in JavaScript. Here are some clever uses:
// Group by propertyconst 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 occurrencesconst 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.