Extracting IDs and sorting them are separate operations. Check whether IDs need numeric comparison or lexical comparison.
Worked example
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(rows.map((r) => r.id).toSorted((a, b) => a - b));Result
[ 1, 2 ]Implementation notes
Sorting a projection avoids changing the original record order. Check for duplicate IDs before treating the result as a unique index.
Try it yourself
Include IDs 2 and 10 and inspect the order.
Open the TypeScript example →Editorial date January 13, 2026 · Published December 6, 2026