Dev Helpers
← Back

Sort using a union direction

Sort using a union direction using TypeScript.

Open this example in the interactive library

Source code

type Row = { id: number; name: string; rank: number | null };
const rows: Row[] = [
  { id: 2, name: "Beta", rank: null },
  { id: 1, name: "Alpha", rank: 3 },
];
console.log(
  ((direction: "asc" | "desc") =>
    rows.toSorted((a, b) => (direction === "asc" ? 1 : -1) * (a.id - b.id)))(
    "desc",
  ),
);

Sample output

[
  { id: 2, name: 'Beta', rank: null },
  { id: 1, name: 'Alpha', rank: 3 }
]