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:

Service Workers — Offline-First Apps Made Easy

Service Workers — Offline-First Apps Made Easy

JavaScript: Fix a Promise.race Call That Silently Leaks Unhandled Rejections From Every Promise That...

JavaScript: Fix a Promise.race Call That Silently Leaks Unhandled Rejections From Every Promise That...

JavaScript Promise.all and Promise.race: Master Async Control

JavaScript Promise.all and Promise.race: Master Async Control

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,056)
  • Get the User Name and Domain Name from an Email Address in SQL (982)
  • How to add default value for Entity Framework migrations for DateTime and Bool (980)
  • Get the First and Last Word from a String or Sentence in SQL (859)
  • 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 (657)
  • Add Constraint to SQL Table to ensure email contains @ (612)
  • 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 (548)
  • Find numbers with more than two decimal places in SQL (477)

Recent Posts

  • HTML5: Fix a datalist Suggestion List Not Filtering as You Type
  • WordPress: Fix a Custom Field Resetting After Every Autosave
  • Docker: Fix a Healthcheck Marking a Container Unhealthy Too Soon
  • Windows 11: Fix Voice Typing Placing Punctuation in the Wrong Spot
  • Git: Fix a Stash Pop Conflicting With Unrelated Untracked Files
  • Photoshop: Fix the History Brush Reverting Past a Resize Step
  • SQL Server: Fix a View Returning Stale Data After a Schema Change
  • CSS: Fix an aspect-ratio Box Collapsing When Content Overflows
  • Photoshop: Fix the Color Picker Clamping a Custom Swatch’s Hue
  • JavaScript: Fix Array.sort Reordering Equal Items Unexpectedly

Most Viewed Posts

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

Recent Posts

  • HTML5: Fix a datalist Suggestion List Not Filtering as You Type
  • WordPress: Fix a Custom Field Resetting After Every Autosave
  • Docker: Fix a Healthcheck Marking a Container Unhealthy Too Soon
  • Windows 11: Fix Voice Typing Placing Punctuation in the Wrong Spot
  • Git: Fix a Stash Pop Conflicting With Unrelated Untracked Files

Social

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