Sub topic 10
From Groups to Summaries: Counting, Summing, and Reshaping
This chapter assumes you can already call Object.groupBy and Map.groupBy, and that you know Object.entries, Object.fromEntries, and Array.prototype.reduce. Grouping is usually the middle step. The next step turns each array of elements into a number, a list of names, or some other smaller value.
The Pattern: Entries In, Entries Out
A grouped object maps each key to an array. To summarize it, convert it to [key, array] pairs, replace each array with a summary, and build a new object from the pairs.
Object.entries works on the null-prototype result because it is a static function and does not depend on inherited methods. The object that Object.fromEntries returns is an ordinary object with Object.prototype.
Counting and Summing
To count the elements in each group, replace each array with its length. To sum a field, reduce each 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 counts = Object.fromEntries(
Object.entries(byType).map(([type, items]) => [type, items.length])
);
const totals = Object.fromEntries(
Object.entries(byType).map(([type, items]) => [
type,
items.reduce((sum, item) => sum + item.quantity, 0),
])
);
console.log(counts); // { vegetables: 1, fruit: 2, meat: 1 }
console.log(totals); // { vegetables: 5, fruit: 5, meat: 23 }The keys keep the order they had in the grouped object, so the summary lists types in the same order as the groups.
Reshaping Groups
A summary doesn't have to be a number. You can keep only the fields you need, or pick one representative element from each group.
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 mapGroups = (groups, fn) =>
Object.fromEntries(
Object.entries(groups).map(([key, items]) => [key, fn(items, key)])
);
const names = mapGroups(byType, (items) => items.map((i) => i.name));
const largest = mapGroups(byType, (items) =>
items.reduce((a, b) => (b.quantity > a.quantity ? b : a)).name
);
console.log(names.fruit); // ["bananas", "cherries"]
console.log(largest); // { vegetables: "asparagus", fruit: "cherries", meat: "goat" }A small helper like mapGroups keeps the entries-map-fromEntries pattern in one place, so each summary is a single line.
Summarizing a Map
With Map.groupBy, spread the Map into pairs and pass the mapped pairs to new Map. The keys keep their original types.
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 byStocked = Map.groupBy(inventory, ({ quantity }) => quantity > 5);
const countByStocked = new Map(
[...byStocked].map(([key, items]) => [key, items.length])
);
console.log(countByStocked.get(false)); // 3
console.log(countByStocked.get(true)); // 1Don't use Object.fromEntries here unless you want the keys converted to strings. false would become "false", and object keys would collapse to "[object Object]".
Common Mistakes
| Mistake | Result | Fix |
|---|---|---|
| Calling `byType.map(...)` | TypeError, because the result is not an array | Use `Object.entries(byType).map(...)` |
| Omitting the initial value in a sum `reduce` | Returns the first element object instead of a number | Pass `0` as the second argument |
| Using `Object.fromEntries` on a Map with object keys | Keys collide as `"[object Object]"` | Build a `new Map` instead |
Exercise
Using the inventory array from this chapter, produce an object with the average quantity for each type, for example { vegetables: 5, fruit: 2.5, meat: 23 }.
Show answer
const byType = Object.groupBy(inventory, ({ type }) => type); const averages = Object.fromEntries(Object.entries(byType).map(([type, items]) => [type, items.reduce((sum, i) => sum + i.quantity, 0) / items.length])); Every group has at least one element, so the division is never by zero.
Exercise
You grouped with Map.groupBy using object keys and want a Map from each key to the list of item names. Why not use Object.fromEntries, and what should you write instead?
Show answer
Object.fromEntries converts every object key to the string "[object Object]", so all groups would overwrite one another. Write new Map([...groups].map(([key, items]) => [key, items.map((i) => i.name)])) to keep the original key references.