Map.groupBy Groups By Object Identity
Group records with Map.groupBy using object keys, compare identity with a structural clone, and contrast the result with Object.groupBy string keys.
Code
const region = { name: "eu" };
const fallback = { name: "us" };
const orders = [
{ id: 1, market: region },
{ id: 2, market: fallback },
{ id: 3, market: region },
{ id: 4, market: { name: "eu" } },
];
const grouped = Map.groupBy(orders, (order) => order.market);
console.log("groups:", grouped.size);
console.log("eu ids:", grouped.get(region).map((order) => order.id));
console.log("fallback ids:", grouped.get(fallback).map((order) => order.id));
// A structurally equal but distinct object is a different Map key.
const clone = { name: "eu" };
console.log("clone group:", grouped.get(clone));
const byName = Object.groupBy(orders, (order) => order.market.name);
console.log("string keys:", Object.keys(byName));
console.log("eu count:", byName.eu.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
groups: 3
eu ids: [ 1, 3 ]
fallback ids: [ 2 ]
clone group: undefined
string keys: [ 'eu', 'us' ]
eu count: 3How the snippet works
Module-level bindings hold the data — region, fallback, orders, grouped — with no function scope in between.
The top-level object literal pins name as plain values — no derivation, no imports behind them.
Watch out for
- Zero third-party dependencies — the runtime provides every API used here.
Putting it to use
The demo output is labeled (groups:, eu ids:, fallback ids:), so every printed line maps back to its originating operation.
Core lines
const byName = Object.groupBy(orders, (order) => order.market.name);
const grouped = Map.groupBy(orders, (order) => order.market);
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `region`, `fallback`, `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.