#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

  • The array may be empty
  • Every key that fn produces is a string

Notes

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

How to solve it

Bucketing

Grouping is the operation reduce was made for, and it is now a real language feature: Object.groupBy and Map.groupBy ship in modern browsers. Implementing it by hand is still asked because the failure mode is interesting.

Approach

For each item, compute the key, ensure a bucket, push.

Implementation

JSfile.javascript
1Array.prototype.myGroupBy = function (fn) { 2 const out = {}; 3 for (let i = 0; i < this.length; i += 1) { 4 const key = fn(this[i], i, this); 5 if (!Object.prototype.hasOwnProperty.call(out, key)) out[key] = []; 6 out[key].push(this[i]); 7 } 8 return out; 9};

Worth knowing

out[key] = out[key] || [] looks correct and is not. Every plain object inherits constructor, toString and valueOf from its prototype, and all of them are truthy — so grouping by a key that happens to be "constructor" finds a truthy value and calls .push on a function. hasOwnProperty avoids it, and Object.create(null) avoids it structurally by making an object with no prototype at all.

Order inside a bucket must match the input, so walk forwards and append.

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

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 · Polyfills — Pratik Rai ·

JavaScript

Object.assign Polyfill

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

JavaScript · Objects · Polyfills — Pratik Rai ·

JavaScript

Object.create Polyfill

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

JavaScript · Objects · Prototypes — Pratik Rai ·