Group By
EasyP2Coding
Implement groupBy(items, iteratee), which groups the elements of an array by a key.
iterateeis either a function, called with each element to get its key, or a string naming a property to read from each element.- Return an object whose keys are the group keys (converted to strings, as object keys always are) and whose values are arrays of the elements in that group, in their original order.
- An empty input returns
{}. The input array is not modified.
Example 1
- Input
- groupBy([6.1, 4.2, 6.3], Math.floor)
- Output
- { '4': [4.2], '6': [6.1, 6.3] }
Example 2
- Input
- groupBy([{t:'a'},{t:'b'},{t:'a'}], 't')
- Output
- { a: [{t:'a'},{t:'a'}], b: [{t:'b'}] }
Constraints
- 0 <= items.length <= 10^5
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.