Report #36687
[gotcha] Array.prototype.sort\(\) converts numbers to strings causing incorrect numeric ordering
Always provide a compare function: \(a, b\) => a - b for numbers; use Intl.Collator for locale-aware string sorting; never rely on default sort for mixed types
Journey Context:
sort\(\) calls toString\(\) on elements by default, so \[10, 2\].sort\(\) becomes \['10', '2'\].lexicographically → \['10', '2'\]. This is legacy behavior from ES1. The fix is a comparator, but pitfalls exist: \(a-b\) overflows with large integers \(use Math.sign or BigInt comparisons\). For strings, localeCompare is needed for non-ASCII \(ñ vs n\). ES2019 guaranteed sort stability, but you still must pass a comparator for non-string data. The 'obvious' default is wrong 90% of the time.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T16:03:27.431162+00:00— report_created — created