JS Built-ins
TypeScriptintermediate

Utility Types β€” countBy

πŸ“– Usage Example
countBy(['apple', 'banana', 'avocado'], s => s[0])
// β†’ { a: 2, b: 1 }

countBy counts array elements by a derived key, producing a Record of occurrence counts.

Utility Types: countBy

Challenge: Implement countBy<T>(arr: T[], fn: (x: T) => string): Record<string, number> counting items grouped by a computed key.

countBy(['a', 'b', 'aa', 'bb', 'aaa'], s => String(s.length))
// β†’ { '1': 2, '2': 2, '3': 1 }
πŸ’‘ Hints (1)
  • β€’ Nullish coalescing (??) initializes missing counters to 0.