← Fundamentals
Fundamentals

Ordering, sorting, and comparators

What does this comparison promise beyond one pair?

Treat a comparator as a consistent ordering policy for the whole collection.

Outcome

Use the native callback category, preserve stable key equivalence and audit a finite proposed strict weak order without executing invalid sorting.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Comparison-equivalent
Two values for which neither strict less-than direction holds under the chosen ordering key.
Stable sorting
Sorting that preserves prior relative order within a comparison-equivalent group.
Strict weak order
An irreflexive transitive before relation whose induced comparison-equivalence is also transitive.
Three-way comparison
An ordering result distinguishing before, equivalent and after, rather than only a boolean before predicate.

An ordering is a relation

Sorting arranges values according to an ordering relation. A comparator expresses that relation for a pair, using the result form required by its native API. The callback’s accepted type and the consistency of its ordering are separate requirements.

A stable sort preserves the input order among values that its comparison treats as equivalent. Define the keys, the treatment of ties and any missing values before choosing a sorting pass. A policy must remain coherent across many comparisons, not merely produce a plausible answer for one pair.

01Native numeric order

The default comparison is not the same everywhere

An issue-triage queue lists lower scores first and keeps arrivals in their incoming order when scores tie. A score report, an ID-indexed export and a proposed new ranking callback all use comparison code. The same sorting pass can be correct for one of those jobs and wrong for another.

Start with the queue’s numeric score report. Its native sort receives the values 2, 10 and 1. Predict the order before choosing a callback for issue records.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const scores = [2, 10, 1];
scores.sort();

console.log("scores", ...scores);
Which outcome follows from the shown source?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts

Save one complete example at a time in a fresh folder under the selected filename. Run the shown checking/build command before execution. The browser lab supplies its editor, stdin fixtures and native runner.

02Callback result categories

Checking catches a real porting mistake

The queue is being ported to another native sorting API. The developer supplies the callback below, carrying over a familiar comparison form. Predict whether the shown checking/build command accepts it and whether execution follows.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const scores = [2, 10, 1];
scores.sort((a, b) => a < b);
Which outcome follows from the shown source?

03Comparison equivalence and stable ties

Stability preserves the input to that pass

The live queue keeps arrival order within a score group. The export instead wants issues indexed by ID within each group: it orders by ID first, then performs a stable score pass. The same three issues arrive as IDs 3, 2, 1. Predict both reports.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const rows = [
  { id: 3, score: 2 },
  { id: 2, score: 1 },
  { id: 1, score: 2 }
];
rows.sort((a, b) => a.id - b.id);

console.log("by-id", ...rows.map((row) => row.id));

rows.sort((a, b) => a.score - b.score);

console.log("by-score", ...rows.map((row) => row.id));
What prints after the ID pass and after the stable score pass?

04The three-value contract

Pairwise and strict-transitivity checks can still miss a fault

A proposed ranking treats an issue with unknown score as incomparable with every issue. The inspector compares three values directly to check what that policy implies. Predict the relation facts; this proposal is never passed to sorting.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const less = (a: number | null, b: number | null) => a !== null && b !== null && a < b;
const equivalent = (a: number | null, b: number | null) => !less(a, b) && !less(b, a);
const a = 0;
const b = null;
const c = 1;

console.log("equiv", equivalent(a, b), equivalent(b, c), "less", less(a, c));
Which outcome follows from the shown source?

05Practice

Repair the queue-ranking regression tests

Repair the live triage queue’s ranking checks. Sort numeric scores, retain incoming arrival order among tied issue records, then classify a proposed comparator on the supplied finite domain. The ID-indexed export from the reading has a different tie policy.

Modes are supplied regression proposals, including deliberately broken relations. The audit evaluates their laws on those rows; it never installs a proposal as the score sorter or certifies unobserved issues.

Start the lab

Order the scores, preserve the live queue’s tie policy with the native callback contract, then implement the finite comparator audit.

  1. easy · F-ORDER-V4-1 Sort numeric scores
  2. medium · F-ORDER-V4-2 Use the native comparator contract
  3. hard · F-ORDER-V4-3 Audit the finite ordering proposal
In the frontend List keys retain item identity; they do not choose the ranking order. Optional

The triage panel receives arrivals and a pure, consistent numeric comparator from its parent. These excerpts sort a new array for display and keep unique issue IDs as rendering keys. The comparator still owns the ranking and tie policy.

The copy protects the incoming array’s order; it retains the same issue objects. This view does not modify their fields. A React key or keyed Svelte each block helps the framework track those items when the array order changes.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Issue = { id: number; score: number };
type Props = {
  arrivals: readonly Issue[];
  compare: (a: Issue, b: Issue) => number;
};

export function TriageList({ arrivals, compare }: Props) {
  const ordered = [...arrivals].sort(compare);

  return (
    <ol>
      {ordered.map((issue) => (
        <li key={issue.id}>
          {issue.id}: {issue.score}
        </li>
      ))}
    </ol>
  );
}

React renders the ordered array and uses each unique key to match an item across renders. key is not an instruction to sort by ID. The comparator must be pure because it runs during rendering; the copied array prevents sort from reordering the arrivals prop.

Sources: React: rendering lists and keys,React: copying before sorting,Svelte: keyed each blocks,Svelte: $derived.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.