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 { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 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.