FrontendInterviews.dev

Loading problem…

93. Group By

Medium•
Acceptance: 71.43%
•
🔓3/3 Pro unlocks today

Implement a groupBy function that groups elements of an array by a key generated by a provided function.

Requirements

1. Basic Functionality

  • Accept an array and a grouping function
  • Group array elements by the key returned by the function
  • Return an object where keys are the grouping keys and values are arrays of elements
  • Support both function and string key selectors

Example Usage

// Group by function
groupBy([1, 2, 3, 4, 5], n => n % 2);
// Returns: { '0': [2, 4], '1': [1, 3, 5] }

// Group by property
groupBy([
  { name: 'John', age: 20 },
  { name: 'Jane', age: 20 },
  { name: 'Bob', age: 30 }
], 'age');
// Returns: { '20': [{ name: 'John', age: 20 }, { name: 'Jane', age: 20 }], '30': [{ name: 'Bob', age: 30 }] }

Constraints

  • The function should handle both function and string key selectors
  • Keys should be converted to strings for object keys
  • Empty arrays should return an empty object
  • Handle null/undefined values in the array
  • Preserve the order of elements within each group