Skip to content

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 a Set Still Contains ‘Duplicate’ Values That Look Completely Identical

- 26.09.26 - ErcanOPAK

⚡ The Set That’s Supposed to Remove Duplicates and Somehow Didn’t

A JavaScript `Set` is built specifically to hold only unique values – but when it’s populated with objects rather than primitives, two items that look completely identical when logged to the console can both end up in the Set, because `Set` uses the exact same reference equality as `===` : two separately-created objects with identical properties are still two different references, and the Set treats them as two different values.

🔎 The Problem

const uniqueUsers = new Set();

uniqueUsers.add({ id: 42, name: "Ayşe" });
uniqueUsers.add({ id: 42, name: "Ayşe" });   // Looks identical...

console.log(uniqueUsers.size);   // 2, not 1

// Set.has() and the uniqueness Set provides are both based on the SAME
// object identity used by ===. Two object literals with identical
// properties are still two separate objects in memory - Set has no
// built-in concept of "these represent the same data," only "is this
// literally the same reference I'"'"'ve already seen."

✅ Fix: Dedupe by a Key, Not by the Object Itself

  • For objects that have a natural unique identifier (an `id` field, as here), build a `Map` keyed by that identifier instead of a `Set` of the objects themselves – `new Map(users.map(u => [u.id, u]))` naturally keeps only the last occurrence for each id, which is usually exactly the deduplication behavior actually wanted.
  • Where no natural key exists, deduplicating by a stable serialized form (`JSON.stringify` of a normalized, key-sorted version of each object) as the Set’s actual stored value works, though it’s worth being careful that two objects considered semantically equal always serialize to an identical string – key order matters to `JSON.stringify` unless it’s explicitly normalized first.
  • A small deep-equality-aware dedupe helper (using Lodash’s `_.uniqBy`, or a hand-rolled comparison for simple cases) is often clearer to read than either of the above once the number of fields that matter for comparison grows past one or two.

⚠️ Why This Is an Easy Assumption to Make

  • `Set` correctly deduplicates primitives (numbers, strings, booleans) by VALUE, which is the far more common use case people reach for `Set` with in the first place – the surprising, reference-based behavior only shows up once objects specifically are added, which can be long after a developer has already formed the (correct, for primitives) mental model that Set just “removes duplicates.”
  • This is worth double-checking anywhere data comes from an API and might contain duplicate records that are structurally identical but were fetched or constructed as separate objects – a naive `new Set(apiResults)` silently does nothing useful in that exact case.

A Set removes exact duplicates, not similar-looking ones – and for objects, ‘exact’ means the same reference, not the same data.

— JavaScript Tip

Related posts:

JavaScript: Master the This Keyword

Why setTimeout(fn, 0) Is NOT Immediate (And Breaks Logic)

JavaScript: Use Temporal API for Modern Date and Time Handling

Post Views: 2

Post navigation

Photoshop: Recover a Layer Group Structure Lost When Copying Between Documents
Git: Fix a Blame Result That Points at an Automated Reformat Instead of the Real Change

Leave a Reply Cancel reply

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

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

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

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (951)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

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