This content originally appeared on DEV Community and was authored by groundhog
Smarter Data Handling:
Working with data arrays in JavaScript, especially when fetched from APIs or user input, often means dealing with imperfections like duplicate entries or missing information. A common challenge is ensuring uniqueness based on a specific property, like an id. But what if some items legitimately don't have an id, and you still want to include them in your final list?
This post dives into a robust JavaScript technique to filter out objects with duplicate IDs, while explicitly preserving any objects that don't have an id property (or whose id is null or undefined).
The Duplicate ID Dilemma
Imagine you have an array of data like this:
const rawData = [
{ id: 1, name: 'Product A' },
{ name: 'Uncategorized Item 1' }, // No ID!
{ id: 2, name: 'Product B' },
{ id: 1, name: 'Product A - Updated' }, // Duplicate ID!
{ id: null, name: 'Null ID Item' }, // ID is null!
{ id: 3, name: 'Product C' },
{ name: 'Uncategorized Item 2' }, // Another item without an ID
];
Our goal is to get a clean array where:
- Each
id(if present) appears only once. - Any item without an
id(or withnull/undefinedas anid) is always included, regardless of other items.
This requires a slightly more nuanced approach than a simple duplicate filter.
The filter() + Set Strategy (with a Twist)
The most effective way to solve this is by combining Array.prototype.filter() with a Set object. The Set is perfect for efficiently tracking unique values (our IDs) because checking if a value has() been added to a Set is very fast.
The "twist" comes in how we handle objects that lack an id.
Let's break down the JavaScript implementation:
function getUniqueItemsPreservingNoId(arr) {
// We use a Set to keep track of IDs we've already encountered.
const seenIds = new Set();
return arr.filter(item => {
const id = item.id; // Get the ID for the current item
// --- IMPORTANT: Handle items without a valid ID first ---
// If 'id' is falsy (undefined, null, 0, etc.), we immediately return true.
// This ensures such items are ALWAYS included in the filtered array.
if (!id) {
return true;
}
// --- For items WITH a valid ID, check for duplicates ---
// Check if we've already seen this specific ID.
const isDuplicate = seenIds.has(id);
// If it's the first time we're seeing this ID, add it to our Set.
if (!isDuplicate) {
seenIds.add(id);
}
// Return true only if it's NOT a duplicate (i.e., it's the first instance of this ID).
return !isDuplicate;
});
}
const uniqueAndPreserved = getUniqueItemsPreservingNoId(rawData);
console.log(uniqueAndPreserved);
What the Result Looks Like
Running the getUniqueItemsPreservingNoId function on our rawData will yield:
[
{ id: 1, name: 'Product A' },
{ name: 'Uncategorized Item 1' },
{ id: 2, name: 'Product B' },
{ id: null, name: 'Null ID Item' },
{ id: 3, name: 'Product C' },
{ name: 'Uncategorized Item 2' }
]
Notice how Product A - Updated (which had a duplicate id: 1) was filtered out, but Uncategorized Item 1, Null ID Item, and Uncategorized Item 2 (all lacking a standard id) were kept.
How It Works: The Breakdown
-
seenIds = new Set(): We initialize an emptySet. This will store all the uniqueidvalues we encounter. -
arr.filter(item => { ... }): Thefiltermethod iterates over eachitemin ourrawDataarray. If the callback function returnstrue, theitemis kept; iffalse, it's discarded. -
if (!id) { return true; }: This is the critical line.- It checks if
item.idis a "falsy" value (i.e.,undefined,null,0,'',false). - If
idisundefinedornull(meaning no valid ID exists), we immediately returntrue. This tellsfilterto keep this item without any further duplicate checks.
- It checks if
-
seenIds.has(id): For items that do have a validid, we check if ourseenIdsSetalready contains thisid. -
seenIds.add(id): If theidhasn't been seen before (isDuplicateisfalse), we add it to ourSet. -
return !isDuplicate;: Finally, for items with anid, we returntrueonly if it's not a duplicate (i.e., it's the first time we've encountered this specific ID).
Connecting the dots...
This filter() and Set combination provides a clean, efficient, and readable way to handle a common data manipulation task. By adding the initial check for !id, you gain the flexibility to enforce uniqueness where it matters (for items with IDs) while gracefully preserving all other data points. Master this pattern, and your data processing logic will be much more robust!
This content originally appeared on DEV Community and was authored by groundhog
groundhog | Sciencx (2025-10-21T02:03:50+00:00) Filtering Duplicates by ID (and Keeping the Rest!) in JavaScript. Retrieved from https://www.scien.cx/2025/10/21/filtering-duplicates-by-id-and-keeping-the-rest-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.