Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Why Array Sort Can Reorder Equal Elements Differently Across Browsers

- 03.10.26 - ErcanOPAK

đź”§ The Sort That Agreed on the Order, Just Not Which Order

Calling sort with a comparator that returns 0 for elements considered equal reads as though those equal elements will simply stay in whatever order they started in – and for years, that assumption was only sometimes true, because the specification didn’t always require a stable sort, leaving engines free to reorder equal elements however their particular sorting algorithm happened to. Modern engines have standardized on stability, but code still running in older browsers, older Node versions, or against array-like objects handled by a different code path can quietly reorder items that a comparator called equal, which is invisible for a short list and very visible for a long one shown to a user who expects a secondary, implicit ordering (like insertion order) to be preserved.

🔎 The Problem

const tasks = [
  { name: "Write report", priority: 2, addedOrder: 1 },
  { name: "Fix bug", priority: 1, addedOrder: 2 },
  { name: "Review PR", priority: 2, addedOrder: 3 },
  { name: "Reply to email", priority: 1, addedOrder: 4 }
];

// Sorting only by priority - the comparator returns 0 for tasks
// that share a priority, silently relying on the engine to leave
// those tied tasks in their original relative order.
tasks.sort((a, b) => a.priority - b.priority);

// On an engine (or a code path) that doesn't guarantee a stable
// sort for ties, "Write report" and "Review PR" - both priority 2 -
// are not guaranteed to come out in the order they went in, even
// though every modern mainstream engine happens to get this right
// today, which is exactly what makes relying on it implicitly risky.

âś… Fix: Make the Secondary Order Explicit in the Comparator

  • Adding addedOrder (or any explicit tiebreaker field) as a second comparison inside the same comparator function – returning the priority difference first, falling back to the addedOrder difference when priorities are equal – removes any dependency on sort stability entirely, since the order is now fully determined by the comparator itself.
  • Checking which JavaScript engines and versions the code actually needs to support, and confirming the ECMAScript specification version they implement guarantees stable sort (true for all current mainstream engines following ES2019 and later), clarifies whether this is a real risk for a given deployment target or a theoretical one.
  • Writing a quick test with a list long enough and tied enough to make a reordering obvious (rather than trusting a three-item example that happens to look fine) is the fastest way to confirm a comparator’s actual behavior on the engines that matter, rather than relying on assumption.

⚠️ Why This Is Easy to Overlook Today

  • Every current major browser engine and Node.js version has implemented a stable Array.prototype.sort for a while now, so code that implicitly relies on stability for ties genuinely works correctly in virtually every environment it’s likely to run in today – right up until it runs somewhere older, or against a library’s custom array-like structure with its own sort implementation.
  • A comparator that returns 0 for ‘equal’ elements is making an implicit claim that it doesn’t care about their relative order – when that claim isn’t actually true (the UI does show an implicit secondary order to the user), the bug isn’t really in the sort engine at all, it’s in the comparator not saying what it actually means.

Returning 0 from a comparator isn’t saying ‘don’t move these’ – it’s saying ‘I don’t care where these end up,’ and sooner or later something takes that literally.

— JavaScript Best Practice

Related posts:

AJAX “Stale Data” — Browser Caching GET Requests Deeply

AJAX “Stale Data” — Browser Caching GET Requests Deeply

JavaScript: Use import.meta to Get Module Information

JavaScript: Use import.meta to Get Module Information

Ajax Requests Succeed but Data Is Outdated

Ajax Requests Succeed but Data Is Outdated

Views: 12

Post navigation

WordPress: Fix a Scheduled Post That Publishes Hours Late Because of Server Time Zone Drift
ASP.NET Core: Fix a Fire-and-Forget Task.Run Call That Silently Disappears When the App Recycles

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com