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 criticalhighmediumlow. 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

  1. Single source of truth – change the ranking object, and every sort immediately follows suit.
  2. Readable – intent is obvious at a glance.
  3. 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.