Array.prototype.groupBy

PolyfillArraysObjects

Add myGroupBy(fn) to Array.prototype.

fn returns the key for each item. The result is an object whose values are arrays of the items sharing that key, in their original order.

Examples

Example 1
Input
[1, 2, 3].myGroupBy((n) => (n % 2 ? 'odd' : 'even'));
Output
{ odd: [1, 3], even: [2] }
Explanation
Each item is appended to the bucket its key names.

Constraints

  • 0 <= array.length <= 10^5
  • fn returns a string key

Notes

  • `out[key] = out[key] || []` breaks when a key is "constructor" or "toString", which are truthy on every object.

Hints

Read the full write-up for Array.prototype.groupBy
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it