Sort Comparators Must Return Numbers
Comparators returning booleans only produce 0 or 1, so descending swaps never apply; subtract the fields instead to get a numeric comparator.
Code
const scores = [
{ name: "ada", points: 12 },
{ name: "bo", points: 9 },
{ name: "cy", points: 12 },
];
// A boolean comparator only ever yields 0 or 1: true reads as
// "a goes after b", false as "leave this pair alone", so no
// comparison ever signals "move a before b"
const broken = [...scores].sort((a, b) => a.points > b.points);
console.log("broken:", broken.map((s) => s.name + ":" + s.points)); // input order came back
// A comparator must return a number: negative, zero, or positive
const byPointsDesc = [...scores].sort((a, b) => b.points - a.points);
console.log("fixed:", byPointsDesc.map((s) => s.name + ":" + s.points));
// sort is stable since ES2019: ada and cy tie, ada keeps its lead
console.log("tie order:", byPointsDesc.map((s) => s.name));Output
Captured from a sandboxed run of this snippet in the build pipeline.
broken: [ 'ada:12', 'bo:9', 'cy:12' ]
fixed: [ 'ada:12', 'cy:12', 'bo:9' ]
tie order: [ 'ada', 'cy', 'bo' ]How it works
Top-level bindings scores, broken, byPointsDesc hold the demo state — nothing sits inside a function scope.
Watch out for
- No package installation, no environment variables, no setup steps.
Using it
Output lines are prefixed (broken:, fixed:, tie order:), which makes the step behind each line recoverable from the text.
Key statements
const byPointsDesc = [...scores].sort((a, b) => b.points - a.points);
const broken = [...scores].sort((a, b) => a.points > b.points);
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `scores`, `broken`, `byPointsDesc`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.