Sometimes you don’t want the default alphabetical or numeric sort—you want your own order. For instance, imagine an array of bug tickets that must appear by severity:
const tickets = [
{ id: 42, severity: 'medium', title: 'Scrollbar jitter' },
{ id: 13, severity: 'critical', title: 'Data loss on save' },
{ id: 77, severity: 'low', title: 'Typo in footer' },
{ id: 31, severity: 'high', title: 'Broken login link' },
];
The desired order is critical
➜ high
➜ medium
➜ low
.
You could chain if/else
blocks, but that’s brittle and hard to read.
First, define the order once:
const severityRank = {
critical: 0,
high: 1,
medium: 2,
low: 3,
};
Then use it in a one‑liner sort
:
tickets.sort(
(a, b) => (severityRank[a.severity] ?? Infinity) -
(severityRank[b.severity] ?? Infinity)
);
That’s it. No gymnastics, no duplicated logic.
Why this pattern rocks
- Single source of truth – change the ranking object, and every sort immediately follows suit.
- Readable – intent is obvious at a glance.
- Safe fallbacks – unknown severities get
Infinity
and sink to the bottom, but you can flip that to-Infinity
if you want them at the top.
Bonus tip
If your “type” strings come from user input, guard against typos:
const rank = severityRank[severity] ?? throw new Error(`Unknown severity: ${severity}`);
You’ll catch mistakes early instead of relying on silent mis‑orderings.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.