Dev Helpers
← Back

Retain the last two revisions per document

Retain the last two revisions per document. Start with typed records and inspect the inferred result.

Open this example in the interactive library

Source code

type Row = { doc: string; rev: number; author: string };
const rows: Row[] = [
  { doc: "guide", rev: 1, author: "Ada" },
  { doc: "api", rev: 1, author: "Leo" },
  { doc: "guide", rev: 3, author: "Kim" },
  { doc: "guide", rev: 4, author: "Ada" },
];
const result = [...new Set(rows.map((r) => r.doc))].flatMap((doc) =>
  rows
    .filter((r) => r.doc === doc)
    .toSorted((a, b) => b.rev - a.rev)
    .slice(0, 2),
);
console.log(JSON.stringify(result, null, 2));

Sample output

[
  {
    "doc": "guide",
    "rev": 4,
    "author": "Ada"
  },
  {
    "doc": "guide",
    "rev": 3,
    "author": "Kim"
  },
  {
    "doc": "api",
    "rev": 1,
    "author": "Leo"
  }
]