coding round · ~10 min
JavaScriptbeginner

Implement groupBy

Write groupBy(arr, keyFnOrPropName) that groups the items of arr into a plain object. If the second argument is a function, call it with each item to get that item's group key; if it is a string, use that property of each item as the key.

  • 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'] }
  • groupBy(users, 'role') → { admin: [...], guest: [...] }
  • groupBy([], (x) => x) → {}

Items keep their original order within each group. Return an ordinary object created with {}, and make sure keys that clash with built-in object properties, like 'constructor' or 'toString', still work.

Define groupBy in the editor. 7 tests will call it.

solution.js
function groupBy(arr, keyFnOrPropName) {
  // keyFnOrPropName is either a function (item => key)
  // or a property name like 'type'.
  // Return an object mapping each key to an array of items.
}

Tests⌘/Ctrl + Enter to run

groups by the result of a function
groups by a property name
works with properties of primitives like length
keeps items in their original order within a group
returns an empty plain object for an empty array
calls the key function once per item
handles keys like 'constructor' and 'toString'
esc