Object.groupBy Splits Counting And Totals

Partition records into null-prototype buckets with Object.groupBy, then derive counts, per-bucket totals, and safe reads of missing buckets.

JavascriptData Integrity

Code

javascriptsnippet
27 lines
const orders = [
  { id: 'o-1', region: 'eu', cents: 1200 },
  { id: 'o-2', region: 'us', cents: 4500 },
  { id: 'o-3', region: 'eu', cents: 800 },
  { id: 'o-4', region: 'apac', cents: 3200 },
  { id: 'o-5', region: 'us', cents: 2700 },
];

const byRegion = Object.groupBy(orders, (o) => o.region);
console.log('regions :', Object.keys(byRegion));
console.log('eu      :', byRegion.eu.map((o) => o.id));

// 计数是聚合而不是分组:对每个桶数一次长度
const tally = Object.fromEntries(
  Object.entries(byRegion).map(([region, group]) => [region, group.length]),
);
console.log('tally   :', tally);

// 每个桶做组内聚合:region 的金额合计来自 reduce
const totals = Object.entries(byRegion).map(([region, group]) => ({
  region,
  cents: group.reduce((sum, o) => sum + o.cents, 0),
}));
console.log('totals  :', totals);

// 缺失桶读出来是 undefined:访问前先判断存在
console.log('missing :', byRegion.latam ?? 'no bucket');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

regions : [ 'eu', 'us', 'apac' ]
eu      : [ 'o-1', 'o-3' ]
tally   : { eu: 2, us: 2, apac: 1 }
totals  : [
  { region: 'eu', cents: 2000 },
  { region: 'us', cents: 7200 },
  { region: 'apac', cents: 3200 }
]
missing : no bucket

Inside the snippet

Top-level bindings orders, byRegion, tally, totals hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (regions :, missing :), so every printed line maps back to its originating operation.

Core lines

const totals = Object.entries(byRegion).map(([region, group]) => ({
  region,
  cents: group.reduce((sum, o) => sum + o.cents, 0),
}));
const byRegion = Object.groupBy(orders, (o) => o.region);

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `orders`, `byRegion`, `tally`.