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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Turning each sort key into a comparator function lets you compose ordering rules declaratively.
- 2Centralizing null and type handling in one comparator keeps mixed-value sorting predictable.
- 3Chaining comparators and stopping at the first non-zero result gives clean tie-breaking across columns.
Related explainers
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
typescript
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common'; import { InjectRedis } from '@nestjs-modules/ioredis'; import Redis from 'ioredis'; import { DataSource } from 'typeorm';
Graceful shutdown hooks in NestJS
graceful-shutdown
lifecycle-hooks
dependency-injection
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/multi-column-sorting-in-typescript-explained-typescript-d4a6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.