CodePark/ problems / groupBy
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Array and collection utilities

groupBy

easyabout 12 minutes in an interview

Implement groupBy(items, iteratee), in the style of lodash's groupBy. It returns an object whose keys are group names and whose values are arrays of the items in that group.

The group of an item comes from iteratee:

  • a function: the group is iteratee(item).
  • a string: the group is the item's property with that name, item[iteratee]. This works on primitives too, so "length" on "three" gives 5.

Rules:

  • Group names are turned into strings with String(...), so true becomes "true" and a missing property becomes "undefined".
  • Items keep their original order inside each group.
  • Group names may be any string, including "toString" or "constructor".
  • An empty array gives {}. Don't modify items.
Input: groupBy([6.1, 4.2, 6.3], Math.floor) Output: { '4': [4.2], '6': [6.1, 6.3] }
Input: groupBy(['one', 'two', 'three'], 'length') Output: { '3': ['one', 'two'], '5': ['three'] }