Free beta: 30 days of full access, no card needed.Sign up free

We use necessary cookies to run the site (sign-in and language). The contact and bug-report forms also use Google reCAPTCHA for spam protection, loaded only if you accept. Privacy policy

Field manual

Sort with a custom comparator

O(n log n)

Sort by a rule that isn't plain ascending order: pass a comparator (or a key function) that encodes ties, multiple keys, or a custom priority.

Signals

sort by multiple fields / tie-break on a second keycustom order (not plain ascending)sort descending, or by a computed key"sort so that X comes before Y when..."reorder objects/records, not raw numbers

Template

// sort by a custom / multi-key order
items.sort((a, b) => {
    if (a.priority !== b.priority) return a.priority - b.priority;
    return a.name.localeCompare(b.name);
});

Looks similar, isn't

  • Fast sort (merge/quick): A comparator isn't a different sorting algorithm; it's how you tell an existing O(n log n) sort what "smaller" means. The sort itself is still merge/quicksort under the hood, only the compare rule changes.

n up to ~1e5..1e6, order defined by a custom rule (not just numeric ascending) -> O(n log n) time, same as the underlying sort. Multiple sort keys or a tie-break rule is the cue to write a comparator, not a new algorithm.

Learn this pattern