Grouping with Object.groupBy and Map.groupBy
Grouping is the step of taking a list and turning it into a collection of shorter lists, one per value of a field: orders by customer, words by first letter, records by status. The operation has two parameters, the items and a callback that returns the key of an item, and JavaScript now has it twice: Object.groupBy returns a plain object of groups, and Map.groupBy returns a Map, which can have keys that are not text.
This lesson uses both, then writes the same function by hand to show what the built-in one does, and counts occurrences, which is the other question a table of groups answers. Both methods need Node.js 21 or newer, so a project on an older release uses the version at the end of the lesson.
Object.groupBy
Object.groupBy(items, keyOf) calls the callback once per item, uses its answer as the group name and collects the items in arrays. The result is an object whose keys are the names, and it has no prototype, so a group called toString is a group and not a method.
const people = [
{ name: 'ada', role: 'admin' },
{ name: 'alan', role: 'editor' },
{ name: 'grace', role: 'admin' },
];
const byRole = Object.groupBy(people, (person) => person.role);
console.log('the groups:', Object.keys(byRole).join(','));
console.log('the admins:', byRole.admin.map((person) => person.name).join(','));
console.log('the editors:', byRole.editor.map((person) => person.name).join(','));
console.log('a group nobody has:', byRole.guest);
console.log('the result has no prototype:', Object.getPrototypeOf(byRole));
node groupby.js
the groups: admin,editor
the admins: ada,grace
the editors: alan
a group nobody has: undefined
the result has no prototype: null
Two groups came out, in the order in which their names first appeared. Each group is an array of the original records and not a copy of them, so a change to a record is visible through both. A group that nobody is in is undefined rather than an empty array, and the last line explains the design: the result has a null prototype, so a group name can be any text without colliding with a method that every object has.
Counting with a Map
Counting is grouping with a number instead of a list, and a Map is the natural place for it when the keys are text. The pattern is the same three lines every time: read the old count with a default of zero, add one, store it back. The program then sorts the pairs by the count.
const words = ['b', 'a', 'b', 'c', 'a', 'b'];
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log('in the order they were first seen:', JSON.stringify([...counts]));
const ranked = [...counts].sort((left, right) => right[1] - left[1]);
console.log('the most common first:', ranked.map(([word, count]) => `${word}=${count}`).join(' '));
console.log('a word that never appeared:', counts.get('d') ?? 0);
node counting.js
in the order they were first seen: [["b",3],["a",2],["c",1]]
the most common first: b=3 a=2 c=1
a word that never appeared: 0
The Map kept the words in the order of their first appearance, which the pairs show. The sort works on the pairs and compares the second item of each, so the word that appears most often comes first. The last line is the reason for ?? 0: a word that is not in the map has no count, and a program that prints its counts wants a zero there and not undefined.
Map.groupBy and keys that are not text
When the key of a group is an object, the object version cannot hold it: the key becomes the text [object Object] and every group falls into one. Map.groupBy keeps the keys as they are, so orders can be grouped by the customer object itself, and the map is walked with the same loop as any other.
const ada = { id: 10, name: 'ada' };
const alan = { id: 11, name: 'alan' };
const orders = [
{ id: 1, customer: ada, total: 5 },
{ id: 2, customer: alan, total: 7 },
{ id: 3, customer: ada, total: 9 },
];
const byCustomer = Map.groupBy(orders, (order) => order.customer);
console.log('groups:', byCustomer.size);
console.log('the orders of ada:', byCustomer.get(ada).map((order) => order.id).join(','));
for (const [customer, list] of byCustomer) {
const total = list.reduce((sum, order) => sum + order.total, 0);
console.log(`${customer.name}: ${list.length} order(s), total ${total}`);
}
node mapgroupby.js
groups: 2
the orders of ada: 1,3
ada: 2 order(s), total 14
alan: 1 order(s), total 7
The two customers gave two groups, and get with the object itself found the list, which is the lookup the object version cannot offer. The loop destructures each entry and reduces the totals inside the group, so one pass over the map is enough for the report. The count is right because every order refers to the same two customer objects: an order that held a copy of a customer would open a third group.
Grouping by hand
The written version is a loop, a check with has and a push, and it makes the behaviour of the built-in method easy to see. It is also the version to use on a release that has no groupBy, and the place to add a step the built-in method does not have, such as a key that is computed from two fields.
function groupBy(items, keyOf) {
const groups = new Map();
for (const item of items) {
const key = keyOf(item);
if (!groups.has(key)) {
groups.set(key, []);
}
groups.get(key).push(item);
}
return groups;
}
const oddEven = groupBy([1, 2, 3, 4, 5], (number) => (number % 2 === 0 ? 'even' : 'odd'));
for (const [key, values] of oddEven) {
console.log(`${key}: ${values.join(',')}`);
}
const byRemainder = Map.groupBy([1, 2, 3, 4, 5], (number) => number % 3);
console.log('Map.groupBy keeps the keys as numbers:', [...byRemainder.keys()].join(','));
const textKeys = Object.groupBy([1, 2, 3, 4, 5], (number) => number % 3);
console.log('Object.groupBy turns them into text:', Object.keys(textKeys).join(','));
node hand.js
odd: 1,3,5
even: 2,4
Map.groupBy keeps the keys as numbers: 1,2,0
Object.groupBy turns them into text: 0,1,2
The written function returned a Map, so the two groups are in the order of their first item, which is why the odd numbers came first. The last two lines put the two built-in methods on the same numbers: the Map kept them as 1, 2 and 0 in that order, and the object turned each one into text and then listed the keys that look like indexes in ascending order. That is the difference of the previous lesson appearing in the result of a grouping call.
Exercises
- Group the people in groupby.js by the first letter of the name instead of the role. Which groups come out, and in what order?
- Add a count of the words with one letter in counting.js. Which words are in that group and how many are there?
- Group the orders in mapgroupby.js by a customer that is a copy of ada. How many groups does the map have then, and why?
- Change the written groupBy to return an object instead of a Map, then group the numbers by their remainder. Which order do the keys show?
- Count how many orders each customer has with Object.groupBy and a map over the groups. Which line of the output would become a number?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Object.groupBy(items, keyOf)return?Answer
An object whose keys are the group names and whose values are arrays
Each key of the result is a group name and each value is the list of items with that name.
-
What does the callback of groupBy return?
Answer
The key of the group the item belongs to
The return value of the callback is the group name, so one item lands in one group.
-
What does this program print?
const g = Object.groupBy([1, 2, 3], (n) => (n % 2 ? "odd" : "even")); console.log(Object.keys(g).join(","));Answer
odd,even
The keys are the group names in the order in which the callback first returned them, and the first item is odd.
-
Why can an object returned by
Object.groupByhold a group calledtoStringwithout a problem?Answer
The result has a null prototype, so nothing is inherited
A null prototype means a lookup finds only the keys the grouping created.
-
What does this program print?
const m = Map.groupBy([1, 2, 3], (n) => n % 2); console.log(m.get(1).length, m.get(0).length);Answer
2 1
The odd numbers 1 and 3 are in the group of key 1, and 2 is alone in the group of key 0.
-
Where does
Map.groupBydiffer fromObject.groupBy?Answer
The keys stay the values the callback returned, so objects and numbers are kept as they are
An object converts every key to text, while a Map keeps any value as a key.
-
What does a group name that no item has look like in the result of
Object.groupBy?Answer
The key is absent, so reading it gives undefined
Only keys that the callback produced exist in the result, and the null prototype adds none.
-
What does this program print?
const words = ["a", "b", "a"]; const counts = new Map(); for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1); console.log([...counts.values()].join(","));Answer
2,1
The values are in the order of the keys, and a was counted twice before b was counted once.
-
What does this program print?
const m = Map.groupBy(["a", "bb", "c"], (word) => word.length); console.log(m.get(1).length, m.get(2).length);Answer
2 1
Two words have length one and one word has length two, and the keys stay the numbers the callback returned.
-
Which release added
Object.groupByandMap.groupBy?Answer
Node.js 21
The methods arrived in the language in 2024 and in Node.js 21, so an older release needs the written version.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev