Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Object.groupBy in JavaScript

75 Object.groupBy, and the bag with no prototype

fair

Group a day of sales by area with Object.groupBy, then group the same rows into buckets computed from the price. Show three things the built-in gets right that a hand-rolled version does not: the object it returns has no prototype, its keys are strings whatever you return, and Map.groupBy keeps the key exactly as it was.

Stuck? Three hints, smallest first
  1. 1. The callback is (item, index) and whatever it returns becomes a key, coerced to a string.
  2. 2. The result comes from Object.create(null), so it has no toString, no constructor and no hasOwnProperty.
  3. 3. That matters because a group named "toString" would collide with an inherited method on a plain {}.

The answer

const sales = [
  { good: 'garri', area: 'Ikeja', kobo: 45000 },
  { good: 'rice', area: 'Yaba', kobo: 450000 },
  { good: 'beans', area: 'Ikeja', kobo: 130000 },
  { good: 'palm oil', area: 'Surulere', kobo: 120000 },
];

const byArea = Object.groupBy(sales, ({ area }) => area);
const areas = Object.keys(byArea);
const ikejaGoods = byArea.Ikeja.map(({ good }) => good);

const byBucket = Object.groupBy(sales, ({ kobo }) => (kobo >= 130000 ? 'wholesale' : 'retail'));
const bucketNames = Object.entries(byBucket).map(([name, rows]) => `${name}:${rows.length}`);

const noPrototype = Object.getPrototypeOf(byArea) === null;
const inheritsNothing = ['toString' in byArea, typeof byArea.hasOwnProperty];

const awkward = Object.groupBy(['a', 'b'], () => 'toString');
const naiveGroupBy = (list, fn) => {
  const out = {};
  for (const item of list) (out[fn(item)] ??= []).push(item);
  return out;
};
let naiveResult;
try {
  naiveResult = naiveGroupBy(['a', 'b'], () => 'toString');
} catch (error) {
  naiveResult = error.constructor.name;
}

const coerced = Object.keys(Object.groupBy([1, 2, 3], (n) => n % 2 === 0));
const missing = Object.keys(Object.groupBy([1], () => undefined));
const keptAsKeys = [...Map.groupBy([1, 2, 3], (n) => n % 2 === 0).keys()];

console.log('by area  :', areas, ikejaGoods);
console.log('buckets  :', bucketNames);
console.log('prototype:', noPrototype, inheritsNothing);
console.log('naive    :', naiveResult, '| built-in:', Object.entries(awkward).map(([k, v]) => [k, v.length]));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('groups come out keyed by whatever the callback returned', areas, ['Ikeja', 'Yaba', 'Surulere']);
test('and each group keeps its rows in input order', ikejaGoods, ['garri', 'beans']);
test('the key can be computed, which is how you bucket a range', bucketNames, ['retail:2', 'wholesale:2']);
test('the result has no prototype at all', noPrototype, true);
test('so it inherits nothing you could collide with', inheritsNothing, [false, 'undefined']);
test('a group called toString is therefore fine', Object.entries(awkward).map(([k, v]) => [k, v.length]), [['toString', 2]]);
test('the same grouping over a plain object literal throws instead', naiveResult, 'TypeError');
test('an object key is always a string, so booleans and undefined are stringified', [coerced, missing], [[['false'], ['true']].flat(), ['undefined']]);
test('Map.groupBy keeps the key it was given, type and all', keptAsKeys, [false, true]);

Object.groupBy is the one-line version of the accumulator everyone writes by hand, and the interesting part is what it returns: an object with a null prototype. That is not a detail. Group by a user-supplied string and a plain {} accumulator hands you Object.prototype.toString the moment someone's data says "toString", so (out[key] ??= []).push(...) tries to push onto a function and throws. With no prototype there is nothing to inherit and nothing to shadow.

The price of an object is that keys are strings. Group by a boolean and you get "true" and "false"; group by a date, an object or undefined and you get whatever String() makes of it, which for objects is uselessly "[object Object]". Map.groupBy is the same function with real keys: booleans stay booleans, and object keys compare by identity.

Two smaller things. Each group preserves the input order, so grouping is stable and you can sort once beforehand instead of sorting every group. And because the result has no hasOwnProperty, reach for Object.hasOwn(groups, key) or plain key in groups rather than the method you are used to calling on it.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.