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 ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
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.
Input:
JSfile.javascript1[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.
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.
Continue learning with these related challenges
Implement Array.prototype.reduce from scratch, including the tricky no-initial-value path and the empty-array error case.
JavaScript · Arrays · Polyfills — Pratik Rai ·
Implement Object.assign from scratch: copy own enumerable properties (including Symbols) from sources onto the target.
JavaScript · Objects · Polyfills — Pratik Rai ·
Implement Object.create using the classic empty-constructor trick to set an object's prototype chain.
JavaScript · Objects · Prototypes — Pratik Rai ·
Implement Array.prototype.reduce from scratch, including the tricky no-initial-value path and the empty-array error case.
JavaScript · Arrays · Polyfills
Pratik Rai ·
Implement Object.assign from scratch: copy own enumerable properties (including Symbols) from sources onto the target.
JavaScript · Objects · Polyfills
Pratik Rai ·
Implement Object.create using the classic empty-constructor trick to set an object's prototype chain.
JavaScript · Objects · Prototypes
Pratik Rai ·