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: Fix Array.sort Reordering Equal Items Unexpectedly

- 18.11.26 - ErcanOPAK

⚡ JavaScript: Fix Array.sort Reordering Equal Items Unexpectedly

Every modern engine’s Array.prototype.sort is specified to be stable, meaning elements the comparator treats as equal keep their original relative order — but that guarantee only holds if the comparator itself behaves like a real comparator. A comparator that subtracts a field which can be undefined for some items doesn’t return 0 for ties, it returns NaN, and NaN breaks the total ordering sort relies on, producing results that look like instability even though the sort algorithm underneath is perfectly stable.

🔎 The Problem

const items = [
  { name: 'a', value: 3 },
  { name: 'b' },            // value is undefined
  { name: 'c', value: 3 },
];

items.sort((x, y) => x.value - y.value);
// undefined - 3  === NaN
// NaN is not a valid ordering result -> relative order of items
// involving 'b' is effectively unpredictable, even though sort()
// itself is stable for every comparison that returned a real number

✅ Fix: Make the Comparator Always Return a Real Signed Number

  • Normalize missing or non-numeric fields to an explicit value before comparing, such as treating a missing value as 0 or as a dedicated “always last” sentinel, so the subtraction never produces NaN.
  • Return exactly 0 for genuine ties rather than letting an edge case produce NaN or an inconsistent sign, since a real 0 is what tells the stable sort to preserve original order for those items.
  • Add an explicit secondary tie-breaker key, like original index or name, whenever the primary field can legitimately be equal across multiple items and the exact tie order matters to your output.

🚨 Why This Is Dangerous

  • A sort that behaves inconsistently only on records with a missing field can pass every test built from complete sample data and still misbehave in production the first time a real record arrives with that field left out.

Array.sort kept its promise to be stable — the comparator that returned NaN broke its half of the bargain first.

— JavaScript Tip

Related posts:

JavaScript: Fix a Map Used as a Cache Growing Forever Because Object Keys Inserted Into It Are Compa...

JavaScript: Fix a Map Used as a Cache Growing Forever Because Object Keys Inserted Into It Are Compa...

JS “Object Mutation Side Effects” — The Hidden Reference Bug

JS “Object Mutation Side Effects” — The Hidden Reference Bug

JavaScript: Working with Dates and Times

JavaScript: Working with Dates and Times

Views: 4

Post navigation

Git: Fix a Merge Driver Being Ignored for One File Type
Photoshop: Fix the Color Picker Clamping a Custom Swatch’s Hue

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,059)
  • Get the User Name and Domain Name from an Email Address in SQL (983)
  • How to add default value for Entity Framework migrations for DateTime and Bool (981)
  • Get the First and Last Word from a String or Sentence in SQL (861)
  • How to select distinct rows in a datatable in C# (856)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (658)
  • Add Constraint to SQL Table to ensure email contains @ (613)
  • Average of all values in a column that are not zero in SQL (571)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (549)
  • Find numbers with more than two decimal places in SQL (477)

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK
  • Git: Fix a Worktree Locking a Branch Needed Somewhere Else
  • Asp.Net Core: Fix a Background Service Leaking Scoped Dependencies
  • SQL Server: Fix a Columnstore Index Fragmenting After Bulk Deletes
  • Docker: Fix a Container Losing Logs After a Restart Policy
  • Asp.Net Core: Fix Output Caching Serving a Stale Authorized Page

Most Viewed Posts

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

Recent Posts

  • Visual Studio: Fix Quick Actions Hiding Behind a Stale Squiggle
  • Photoshop: Fix a Smart Filter Resetting After You Relink It
  • Ajax: Fix a Cancelled Request Still Updating Stale UI State
  • C#: Fix a Span Captured by a Lambda Throwing at Runtime
  • The AI Prompt That Converts a REST Endpoint Into a Typed SDK

Social

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