#Polyfill#Arrays

Array.prototype.groupBy

Group an array into buckets by a key function — now a real language feature as Object.groupBy.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1[1, 2, 3].myGroupBy((n) => (n % 2 ? 'odd' : 'even'));

Output:

{ odd: [1, 3], even: [2] }

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.

Goal: Bucket every item under its key, preserving order inside each bucket.

Source

Frequently asked questions

What does groupBy do?
It turns a flat array into an object of buckets, where each bucket holds the items that produced the same key. It is the shape behind most report and category views.
Why is out[key] = out[key] || [] unsafe?
Because every plain object inherits `constructor`, `toString` and `valueOf`, and all of them are truthy. Grouping by a key called `"constructor"` finds an inherited function and tries to push onto it.
How do you avoid prototype keys entirely?
Use `Object.create(null)` for the result, which creates an object with no prototype and therefore no inherited keys, or guard every lookup with `Object.prototype.hasOwnProperty.call`.
Is there a built-in version now?
Yes — `Object.groupBy` and `Map.groupBy` are available in current browsers and Node. `Map.groupBy` is the better choice when keys are not strings, since object keys are always coerced to strings.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Array.prototype.reduce Polyfill

Implement Array.prototype.reduce from scratch, including the tricky no-initial-value path and the empty-array error case.

JavaScript · Arrays · PolyfillsPratik Rai ·

JavaScript

Object.assign Polyfill

Implement Object.assign from scratch: copy own enumerable properties (including Symbols) from sources onto the target.

JavaScript · Objects · PolyfillsPratik Rai ·

JavaScript

Object.create Polyfill

Implement Object.create using the classic empty-constructor trick to set an object's prototype chain.

JavaScript · Objects · PrototypesPratik Rai ·