Implement groupBy
EasyArrays10 min4 tests
Implement a groupBy function that groups array elements by a key returned by a callback function.
Requirements
- Accept an array and a callback that returns the grouping key
- Return an object where keys are group names and values are arrays of matching elements
Example
groupBy([6.1, 4.2, 6.3], Math.floor); // { '4': [4.2], '6': [6.1, 6.3] }Hints (3)
- Use
reduceto accumulate an object. - For each element, compute the key via the callback.
- Initialize the key array if it doesn't exist, then push the element.
Topics
- Arrays
Asked at
Google · Stripe · LinkedIn
