Sub topic 3
From Groups to Summaries: Counting, Summing, and Reshaping
This chapter assumes you already know how to call Object.groupBy and Map.groupBy, and that you can use Object.entries, reduce, and Map methods.
From Groups to Summaries
Grouping is usually the first step toward a summary. To turn a grouped object into one value per key, use Object.entries, then map over the groups and rebuild the object with Object.fromEntries.
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 same idea works for a Map. Use new Map([...map].map(...)) to rebuild it.
Grouping Other Iterables
Both methods accept any iterable, so you can pass strings, Sets, and generators without converting them to arrays first.
const parity = Object.groupBy(new Set([1, 2, 3, 4]), (n) =>
n % 2 ? "odd" : "even"
);
console.log(parity.odd); // [1, 3]Groups Share References
The group arrays are new arrays, but the elements inside them are the original objects. If you change a grouped object, the source array shows the same change. Clone the elements first, for example with structuredClone, if you need groups you can change independently.
Key Order
A Map keeps keys in insertion order. A plain object lists integer-like keys first, in ascending numeric order, and then string keys in insertion order.
const keyFor = (s) => (s === "b" ? "10" : "2");
console.log(Object.keys(Object.groupBy(["b", "a"], keyFor))); // ["2", "10"]
console.log([...Map.groupBy(["b", "a"], keyFor).keys()]); // ["10", "2"]Support and a Fallback
| Runtime | First version |
|---|---|
| Chrome / Edge | 117 |
| Firefox | 119 |
| Safari | 17.4 |
| Node.js | 21 |
TypeScript has included the types since 5.4. To use them, set lib to ES2024 or ESNext. For older runtimes, use a small fallback that also returns a null-prototype object:
function groupBy(items, keyFn) {
const groups = Object.create(null);
let index = 0;
for (const item of items) {
(groups[keyFn(item, index++)] ??= []).push(item);
}
return groups;
}
const group = typeof Object.groupBy === "function" ? Object.groupBy : groupBy;
console.log(group([1, 2, 3], (n) => (n % 2 ? "odd" : "even")).odd); // [1, 3]Exercise
What does Object.keys(Object.groupBy([3, 1, 2], (n) => n)) print, and what would the Map.groupBy version print for its keys?
Show answer
The object version prints ["1", "2", "3"]. The keys become strings, and integer-like keys are sorted in ascending numeric order. Map.groupBy keeps insertion order and the original number type, so its keys are [3, 1, 2].