JavaScriptFundamental (ES6), part 1
groupBy, countBy and indexBy in JavaScript
95 groupBy, countBy and indexBy over a Map
fairWrite the three collectors that turn a flat list into a lookup: groupBy to a list per key, countBy to a number per key, indexBy to one item per key. Let each take either a property name or a function. Return a Map, then show the two things you lose the moment you return a plain object instead.
Stuck? Three hints, smallest first
- 1. Both forms of the key argument reduce to one:
typeof key === 'function' ? key : (item) => item[key]. - 2. For
groupBy, checkmap.has(k)and seed an empty array before pushing. ForcountBy,map.set(k, (map.get(k) ?? 0) + 1)does the same job in one line. - 3.
indexByis the one-liner:new Map(items.map((item) => [of(item), item])). Think about what happens when two items share a key.
const keyFn = (key) => (typeof key === 'function' ? key : (item) => item[key]);
const groupBy = (items, key) => {
const of = keyFn(key);
const out = new Map();
for (const item of items) {
const k = of(item);
if (!out.has(k)) out.set(k, []);
out.get(k).push(item);
}
return out;
};
const countBy = (items, key) => {
const of = keyFn(key);
const out = new Map();
for (const item of items) {
const k = of(item);
out.set(k, (out.get(k) ?? 0) + 1);
}
return out;
};
const indexBy = (items, key) => {
const of = keyFn(key);
return new Map(items.map((item) => [of(item), item]));
};
const riders = [
{ name: 'Chidi', lga: 'Yaba', trips: 41 },
{ name: 'Amaka', lga: 'Ikeja', trips: 12 },
{ name: 'Bisi', lga: 'Yaba', trips: 33 },
{ name: 'Tunde', lga: 'Ikeja', trips: 12 },
{ name: 'Ngozi', lga: 'Surulere', trips: 7 },
];
const names = (list) => list.map((r) => r.name);
const byLga = [...groupBy(riders, 'lga')].map(([k, v]) => [k, names(v)]);
const byBand = [...groupBy(riders, (r) => (r.trips >= 30 ? 'busy' : 'quiet'))].map(([k, v]) => [k, names(v)]);
const perLga = [...countBy(riders, 'lga')];
const perTripCount = [...countBy(riders, 'trips')];
const numericKeyType = typeof [...countBy(riders, 'trips').keys()][0];
const lastPerLga = indexBy(riders, 'lga');
const asObject = Object.fromEntries(countBy(riders, 'trips'));
const boolKeys = [...groupBy(riders, (r) => r.trips > 20).keys()];
console.log('by lga :', byLga);
console.log('by band :', byBand);
console.log('counts :', perLga, '| by trips:', perTripCount);
console.log('indexed :', [...lastPerLga.keys()], '| Yaba ->', lastPerLga.get('Yaba').name);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('grouping by a property gives a list per key, in first-seen order', byLga, [['Yaba', ['Chidi', 'Bisi']], ['Ikeja', ['Amaka', 'Tunde']], ['Surulere', ['Ngozi']]]);
test('a function key groups by anything you can compute', byBand, [['busy', ['Chidi', 'Bisi']], ['quiet', ['Amaka', 'Tunde', 'Ngozi']]]);
test('countBy is the same walk with a number instead of a list', perLga, [['Yaba', 2], ['Ikeja', 2], ['Surulere', 1]]);
test('a Map key keeps its type, so 12 stays the number 12', [perTripCount, numericKeyType], [[[41, 1], [12, 2], [33, 1], [7, 1]], 'number']);
test('indexBy keeps one item per key, and a repeat overwrites', [lastPerLga.size, lastPerLga.get('Yaba').name, lastPerLga.get('Ikeja').name], [3, 'Bisi', 'Tunde']);
test('turn it into a plain object and the numbers become strings, re-sorted ascending', Object.keys(asObject), ['7', '12', '33', '41']);
test('booleans survive as booleans in a Map', boolKeys, [true, false]);
test('nothing in, an empty Map out, not undefined', [groupBy([], 'lga').size, countBy([], 'lga').size], [0, 0]);
These three are the same loop with a different accumulator, which is why they belong in one exercise. Once the key argument is normalised to a function, the difference between them is one line in the body.
Returning a Map rather than an object is the decision worth defending. An object key is always a string, so grouping by trips gives you '12'; grouping by a boolean gives you 'true'; and a group named 'constructor' or '__proto__' collides with something already on Object.prototype. A Map has none of those problems, keeps insertion order for every key type, and gives you .size for free. The cost is that it will not JSON.stringify, which is why the assertions above all project through [...map].
The re-sorting in the object assertion is the detail people trip over: integer-like keys in a plain object are always enumerated in ascending numeric order, no matter what order you inserted them. Insertion order only holds for keys that do not look like array indices. If the order of your groups is meaningful, a Map is not a preference, it is a requirement.
Object.groupBy and Map.groupBy now ship in current engines and do exactly this. Knowing what the hand-written version does tells you which of the two to reach for.