call(back)

Implement groupBy

Write groupBy(array, iteratee): return an object mapping each key to the items that produced it, in input order.

  • iteratee is a function, or a property name to read from each item, such as "length" or "type".
  • Keys are strings, as object keys always are.
  • Every key must work, including "constructor" and "toString", which a plain {} already inherits.
groupBy([6.1, 4.2, 6.3], Math.floor)   // { "4": [4.2], "6": [6.1, 6.3] }
groupBy(["one", "two", "three"], "length")   // { "3": ["one", "two"], "5": ["three"] }

Object.groupBy and Map.groupBy are switched off while your code runs. The functions named in the tests (floor, identity and parity) are supplied by the grader.

Hints

Hint 1

Turn a string iteratee into (item) => item[iteratee] once, at the top.

Hint 2

A plain {} answers out.constructor with the Object function, so (out[key] ??= []) finds a function and .push throws. Start from Object.create(null), or check Object.hasOwn(out, key).

Asked at