Dev HelpersOpen library
← Back

Group records by field

Group records by field. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const rows = [
  { type: "a", id: 1 },
  { type: "b", id: 2 },
  { type: "a", id: 3 },
];
console.log(
  rows.reduce((out, row) => {
    (out[row.type] ??= []).push(row);
    return out;
  }, {}),
);

Sample output

{
  a: [ { type: 'a', id: 1 }, { type: 'a', id: 3 } ],
  b: [ { type: 'b', id: 2 } ]
}