JavaScript

Group records with Object.groupBy

Object.groupBy collects iterable values into arrays under keys returned by a callback. Use it when a report needs one group per status or another simple category.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const jobs = [{id: 1, status: "open"}, {id: 2, status: "done"}, {id: 3, status: "open"}];
const groups = Object.groupBy(jobs, job => job.status);
console.log(groups.open.length, groups.done.length);

How it works

The callback chooses the destination group for every record. The resulting object has a null prototype, and each value is an array of original records in encounter order. No special setup is required for the first occurrence of a status.

Limits and mistakes

Records inside the groups are shared references rather than clones. Keys become property keys, so use Map.groupBy when object identity should define categories. Check support in older browsers before shipping this API.

Check the result

Expect 2 and 1. Add a status named constructor to see why avoiding inherited object properties is helpful. Check absent groups before accessing their length.

Sources

Reference documentation for the behavior used in this guide: