Sub topic 10
From Groups to Summaries: Counting, Summing, and Reshaping
A grouped result is rarely the final answer. Usually you want something smaller from it: how many items each group has, a total per group, a sorted list of rows for a table, or a nested breakdown. This chapter shows the patterns that turn Object.groupBy and Map.groupBy output into those summaries. It also covers the edge cases that trip people up along the way.
This chapter assumes you already know how to call both groupBy methods. It also assumes you are comfortable with Array.prototype.map, reduce, sort, destructuring, and the nullish coalescing operator ??.
The Core Pattern: entries, map, fromEntries
A grouped object maps each key to an array of elements. A summary maps each key to a single value. To get from one to the other, you transform each [key, array] pair into a [key, value] pair. JavaScript has no mapValues built in, so the usual approach takes three steps:
Object.entries(groups)turns the object into an array of[key, items]pairs..map(...)replaces eachitemsarray with a computed value.Object.fromEntries(...)builds a new object from the pairs.
Object.entries works on the null-prototype result without trouble. It reads only own enumerable properties and never needs inherited methods.
Counting Items per Group
The simplest summary is a count. Each group's value is its array's length.
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const counts = Object.fromEntries(
Object.entries(byType).map(([type, items]) => [type, items.length])
);
console.log(counts); // { vegetables: 1, fruit: 2, meat: 1 }When you only need counts
groupBy builds an array for every group. If the only thing you keep is the length, those arrays are wasted work. For large inputs, count directly instead:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const countByType = new Map();
for (const { type } of inventory) {
countByType.set(type, (countByType.get(type) ?? 0) + 1);
}
console.log(countByType.get("fruit")); // 2
console.log(countByType.get("dairy") ?? 0); // 0For a few thousand elements the difference doesn't matter, and the groupBy version is easier to read. Reach for the direct count when profiling shows grouping is a cost, or when the input is a stream too large to hold in memory.
Summing and Other Reductions
Any reduce over a group's array gives you a per-group aggregate. Here is the total quantity per type:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const totals = Object.fromEntries(
Object.entries(byType).map(([type, items]) => [
type,
items.reduce((sum, item) => sum + item.quantity, 0),
])
);
console.log(totals); // { vegetables: 5, fruit: 5, meat: 23 }Always pass the initial value 0 to reduce. A group from groupBy is never empty, so leaving it out won't throw here. It will, however, make the accumulator the first object instead of a number, and the sum turns into a string like "[object Object]5".
Several statistics at once
You often want more than one number per group. Return an object from the map step:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const stats = Object.fromEntries(
Object.entries(byType).map(([type, items]) => {
const quantities = items.map((item) => item.quantity);
const total = quantities.reduce((a, b) => a + b, 0);
return [
type,
{
count: items.length,
total,
average: total / items.length,
max: Math.max(...quantities),
},
];
})
);
console.log(stats.fruit); // { count: 2, total: 5, average: 2.5, max: 5 }
console.log(stats.meat.average); // 23Dividing by items.length is safe because every group has at least one element. Be careful with Math.max(...array) on very large groups. Spreading hundreds of thousands of arguments can exceed the engine's argument limit, so use a reduce there instead.
Missing Groups Are Absent, Not Empty
groupBy creates a key only when at least one element produces it. If no item is "dairy", the result has no dairy property at all. A summary built from Object.entries inherits that gap. That's a problem when a report or chart expects a fixed set of categories.
Drive the summary from the list of expected keys instead of from the groups:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const categories = ["fruit", "vegetables", "meat", "dairy"];
const report = Object.fromEntries(
categories.map((type) => [type, byType[type]?.length ?? 0])
);
console.log(report); // { fruit: 2, vegetables: 1, meat: 1, dairy: 0 }This version also fixes the key order to match categories. Order taken from Object.entries(byType) depends on which element appeared first, which is fragile for display.
Summarizing a Map.groupBy Result
A Map has no fromEntries counterpart, but its constructor accepts any iterable of pairs. Array.from with a mapping function transforms a Map's entries in one step:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byInStock = Map.groupBy(inventory, ({ quantity }) => quantity > 0);
const stockCounts = new Map(
Array.from(byInStock, ([inStock, items]) => [inStock, items.length])
);
console.log(stockCounts.get(true)); // 3
console.log(stockCounts.get(false)); // 1The keys stay booleans, and if you grouped by objects they stay the same object references. Converting this result with Object.fromEntries would turn true into "true" and objects into "[object Object]", collapsing distinct keys. Keep Map results as Maps until the keys are known to be strings.
Runtimes that support the iterator helpers from ES2025 also let you write new Map(byInStock.entries().map(...)) without the intermediate array. Array.from works everywhere Map.groupBy does.
Reshaping into Rows
Tables, charts, and APIs often want an array of records rather than a keyed object. Map the entries into objects, then sort:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const rows = Object.entries(byType)
.map(([type, items]) => ({
type,
names: items.map((item) => item.name),
total: items.reduce((sum, item) => sum + item.quantity, 0),
}))
.sort((a, b) => b.total - a.total);
console.log(rows.map((row) => row.type)); // ["meat", "vegetables", "fruit"]
console.log(rows[2].names); // ["bananas", "cherries"]vegetables and fruit tie at 5. Array.prototype.sort is stable, so the tie keeps the order the groups had in the entries list. Add a secondary comparison, such as a.type.localeCompare(b.type), if you need a deterministic tiebreak that doesn't depend on input order.
Nested Grouping
To break each group down further, run groupBy again on each group's array:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const byType = Object.groupBy(inventory, ({ type }) => type);
const nested = Object.fromEntries(
Object.entries(byType).map(([type, items]) => [
type,
Object.groupBy(items, ({ quantity }) => (quantity > 0 ? "inStock" : "out")),
])
);
console.log(Object.keys(nested.fruit)); // ["out", "inStock"]
console.log(nested.fruit.out[0].name); // "bananas"
console.log(nested.meat.out); // undefinedThe outer object is ordinary, because fromEntries built it. Each inner object is a null-prototype groupBy result. Missing inner groups are still undefined, so read them with ?. and ??, as in nested.meat.out?.length ?? 0.
An alternative is to group once with a composite key such as ` ${type}|${stock} `. That is flatter and faster to build, but you have to split the key apart again to use it. Choose nesting when you will navigate by level, and choose composite keys when you only need lookups by the full pair.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| `reduce` without an initial value on objects | Sums become strings like `"[object Object]5"` | Pass `0` as the second argument |
| Building the summary from `Object.entries` when categories are fixed | Expected keys missing from the report | Map over a list of expected keys and default with `?? 0` |
| `Object.fromEntries` on a `Map.groupBy` result | Object keys collapse to `"[object Object]"` | Build a new `Map` with `Array.from` |
| Grouping only to read `.length` on a huge input | Extra memory and time | Count directly with a `Map` |
| `Math.max(...items)` on very large groups | `RangeError` from too many arguments | Use `reduce` to find the maximum |
Exercise
Using the inventory array from this chapter, write an expression that produces an object mapping each type to a comma-separated string of item names, for example { vegetables: "asparagus", fruit: "bananas, cherries", meat: "goat" }.
Show answer
Object.fromEntries(Object.entries(Object.groupBy(inventory, ({ type }) => type)).map(([type, items]) => [type, items.map((item) => item.name).join(", ")])). Group by type, turn the groups into entries, replace each items array with its joined names, then rebuild an object with Object.fromEntries.
Exercise
A dashboard must always show the categories "fruit", "vegetables", "meat", and "dairy" with their total quantity, even if a category has no items. Why does Object.entries(byType) fail to meet this requirement, and what should you map over instead?
Show answer
groupBy creates a key only when at least one element produces it, so "dairy" is absent from byType and also from any summary built from its entries. Map over the fixed category list instead: categories.map((t) => [t, (byType[t] ?? []).reduce((s, i) => s + i.quantity, 0)]), then pass the result to Object.fromEntries. The ?? [] default makes a missing category sum to 0.
Exercise
You grouped orders with Map.groupBy using customer objects as keys. A teammate converts the result with Object.fromEntries(groups) to send it as JSON, and the output has only one key. What happened, and how should the data be reshaped instead?
Show answer
Object.fromEntries converts each key to a property key, and every plain object stringifies to "[object Object]". All the customers collapse into one property, and each later group overwrites the earlier one. Reshape into an array of records instead, for example Array.from(groups, ([customer, orders]) => ({ customerId: customer.id, orderCount: orders.length })), which serializes cleanly.