JSworkinges2024

Object.groupBy and Map.groupBy

Bucket an array in one call.

Object.groupBy and Map.groupBy turn a flat array into named buckets using a callback β€” no reduce boilerplate, no accidental prototype pollution, no manual array initialisation.

The reduce you stop writing

Grouping a list by some key used to mean a reduce with a manual acc[key] ??= [] dance. Object.groupBy(items, callback) does exactly that: it calls callback(item, index) for every element and files the item under the returned key, building a fresh object whose values are arrays.

The returned object has a null prototype β€” there is no inherited toString, constructor, or hasOwnProperty β€” so a user-supplied key like "constructor" can never collide with Object.prototype. That safety is the whole reason this is a static method rather than something you bolt onto arrays.

When you need object keys, reach for Map.groupBy

Object.groupBy coerces every key to a string (or symbol) β€” the same rule as any object property. If you want to group by an actual object, a number that must stay a number, or anything where identity matters, use Map.groupBy(items, callback). It returns a real Map, so the key from your callback is preserved as-is and compared with SameValueZero.

The callback is just a function

Because the second argument is an ordinary callback, the key can be anything you compute: a field, a derived bucket from a threshold, the first letter of a name, a boolean. Return the same value for two items and they land in the same bucket; insertion order within a bucket is preserved.

Grouping is the setup, not the answer

groupBy gets you buckets; you usually follow it with a second pass β€” count each bucket's length, sum a field, pick a max. Pairing Object.groupBy with Object.entries and map covers most "group then summarise" reporting in a few readable lines.

Try it 5 examples

Group by a category field

JSintro
Press Run to execute

The two keys peripherals and displays appear in first-seen order, and each bucket holds its items in input order (Keyboard, Mouse, Webcam) β€” one call replaced the whole acc[key] ??= [] reduce.