Group Items by Key

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write groupBy(items, keyFn) without using Object.groupBy or Map.groupBy. Call keyFn(item, index) once for each item; it returns a string. Return an object, either a plain one or one made with Object.create(null), with one property per key, each an array of the items with that key in their original order. Keys can include names such as toString, constructor and hasOwnProperty that ordinary objects already inherit, so a key can overwrite a method you call on the result (use Object.hasOwn or a null-prototype object). No items give an empty object, and items is never changed. The checks group 200,000 items, so the work must grow in step with the number of items.

Your code must pass

  • Groups the items under each key, in order
  • Passes the item and its index to keyFn
  • Handles keys like toString and constructor
  • Returns an empty object for no items and leaves the input alone
  • Is fast enough for 200,000 items
  • Works without Object.groupBy or Map.groupBy