typescript 38 lines · 6 steps

Multi-column sorting in TypeScript

A generic sort that orders rows by several keys in priority order, with null-safe, type-aware comparisons.

Explained by highlit
1type SortDirection = "asc" | "desc";
2 
3interface SortKey<T> {
4 selector: (row: T) => string | number | Date | null | undefined;
5 direction?: SortDirection;
6}
7 
8function compareValues(a: unknown, b: unknown): number {
9 if (a == null && b == null) return 0;
10 if (a == null) return 1;
11 if (b == null) return -1;
12 
13 if (a instanceof Date && b instanceof Date) {
14 return a.getTime() - b.getTime();
15 }
16 if (typeof a === "number" && typeof b === "number") {
17 return a - b;
18 }
19 return String(a).localeCompare(String(b), undefined, {
20 numeric: true,
21 sensitivity: "base",
22 });
23}
24 
25export function sortByColumns<T>(rows: readonly T[], keys: SortKey<T>[]): T[] {
26 const comparators = keys.map(({ selector, direction = "asc" }) => {
27 const factor = direction === "desc" ? -1 : 1;
28 return (a: T, b: T) => compareValues(selector(a), selector(b)) * factor;
29 });
30 
31 return [...rows].sort((a, b) => {
32 for (const comparator of comparators) {
33 const result = comparator(a, b);
34 if (result !== 0) return result;
35 }
36 return 0;
37 });
38}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Turning each sort key into a comparator function lets you compose ordering rules declaratively.
  2. 2Centralizing null and type handling in one comparator keeps mixed-value sorting predictable.
  3. 3Chaining comparators and stopping at the first non-zero result gives clean tie-breaking across columns.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Multi-column sorting in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code