Object.groupBy Buckets Array Items By Key

Bucket a flat array into a plain record with Object.groupBy: callback-defined keys, undefined for missing buckets, and a null-prototype result.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// Object.groupBy(ES2024):按回调返回值把扁平数组装进一个普通对象,
// 每个键是一个桶,值是落入该桶的元素数组。
const deploys = [
  { service: 'billing', env: 'prod', ms: 412 },
  { service: 'search', env: 'stage', ms: 388 },
  { service: 'email', env: 'prod', ms: 140 },
  { service: 'auth', env: 'stage', ms: 122 },
  { service: 'pdf', env: 'prod', ms: 305 },
];

const byEnv = Object.groupBy(deploys, (d) => d.env);
console.log('prod :', byEnv.prod.map((d) => d.service));
console.log('stage:', byEnv.stage.map((d) => d.service));

// 桶名可以由计算得出:按耗时分成 slow / fast 两档
const bySpeed = Object.groupBy(deploys, (d) => (d.ms > 300 ? 'slow' : 'fast'));
console.log('slow :', bySpeed.slow.map((d) => d.service));
console.log('fast :', bySpeed.fast.map((d) => d.service));

// 结果是无原型对象:只含本次分桶产生的键,读缺失桶得到 undefined
console.log('keys :', Object.keys(byEnv));
console.log('dev bucket:', byEnv.dev);

Output

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

prod : [ 'billing', 'email', 'pdf' ]
stage: [ 'search', 'auth' ]
slow : [ 'billing', 'search', 'pdf' ]
fast : [ 'email', 'auth' ]
keys : [ 'prod', 'stage' ]
dev bucket: undefined

How it works

Module-level bindings hold the data — deploys, byEnv, bySpeed — with no function scope in between.

Applying it

Running the file prints labeled results such as prod :, stage:, slow : — each operation’s effect is visible in the output.

Statements that matter

const bySpeed = Object.groupBy(deploys, (d) => (d.ms > 300 ? 'slow' : 'fast'));
const byEnv = Object.groupBy(deploys, (d) => d.env);

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `deploys`, `byEnv`, `bySpeed`.