@FahadM to JavaScriptEnglish • 4 days ago

How do you remove duplicate objects from a JavaScript array by property?

message-square
0
1
How do you remove duplicate objects from a JavaScript array by property?
@FahadM to JavaScriptEnglish • 4 days ago

To remove duplicate objects from a JavaScript array by a property without mutating the original array, track seen property values in a Set while iterating with Array.prototype.reduce() or a for...of loop (const seen = new Set(); and only keep an object when !seen.has(key)). Using a Set gives O(n) average time complexity—far faster than nested .findIndex() or .some() scans on large arrays—and lets you choose whether to keep the first occurrence or last occurrence for each key.


1. Deduplicating by Property Key Using Set (Keep First Occurrence)

Use a Set to record each seen key value and return a new array containing the first object for every unique key:

// Deduplicate an array of objects by property key, keeping the first match
function uniqueByProperty(items, keySelector) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  const getKey =
    typeof keySelector === "function"
      ? keySelector
      : (item) => item?.[keySelector];

  const seen = new Set();
  const result = [];

  for (const item of items) {
    const key = getKey(item);
    if (!seen.has(key)) {
      seen.add(key);
      result.push(item);
    }
  }

  return result;
}

// Example usage:
const users = [
  { id: 1, name: "Sara" },
  { id: 2, name: "Bilal" },
  { id: 1, name: "Sara Duplicate" }
];

console.log(uniqueByProperty(users, "id"));
// [{ id: 1, name: "Sara" }, { id: 2, name: "Bilal" }]
  • Linear time complexity: Set.prototype.has() and Set.prototype.add() run in average O(1) time, keeping overall deduplication O(n).
  • Supports property names or selectors: Passing a string key like "id" or a function like (u) => u.email.toLowerCase() handles exact or normalized keys cleanly.

2. Keeping the Last Occurrence with a Map

When later duplicates should overwrite earlier ones—such as applying newer updates for the same record ID—store entries in a Map keyed by the property value and extract Array.from(map.values()):

// Deduplicate by property key while keeping the last matching object
function uniqueByPropertyKeepLast(items, key) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  const byKey = new Map();

  for (const item of items) {
    byKey.set(item?.[key], item);
  }

  return Array.from(byKey.values());
}

// Example usage:
const events = [
  { id: "a", status: "queued" },
  { id: "b", status: "done" },
  { id: "a", status: "completed" }
];

console.log(uniqueByPropertyKeepLast(events, "id"));
// [{ id: "b", status: "done" }, { id: "a", status: "completed" }]
  • Preserves insertion order of latest updates: Map retains keys in order of first insertion while updating the stored object reference to the latest match.
  • Non-mutating: The input array and its original object elements are never modified in place.

3. Edge Cases: Missing Keys, Case Sensitivity, and Object References

Be mindful of how Set and Map compare keys (SameValueZero equality, where NaN equals NaN and +0 equals -0) and normalize strings or handle missing properties intentionally before deduplicating:

// Normalize case and guard missing property values before deduplicating
const rawTags = [
  { slug: "JavaScript" },
  { slug: "javascript" },
  {},
  { slug: null }
];

const normalizedTags = uniqueByProperty(
  rawTags.filter((entry) => entry && typeof entry.slug === "string"),
  (entry) => entry.slug.trim().toLowerCase()
);

console.log(normalizedTags); // [{ slug: "JavaScript" }]
  • String case matters: "JS" and "js" are distinct keys in a Set unless normalized with .toLowerCase().
  • Watch undefined and null keys: Objects missing the property evaluate to undefined, so filter or handle missing keys explicitly if undefined should not be treated as a valid group key.