How do you extract distinct unique values from an array of objects in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you extract distinct unique values from an array of objects in JavaScript?

message-square
0

To extract distinct unique values from an array of objects in JavaScript, map each object to the target property or derived key and pass the resulting list into a Set (converting back to an array with Array.from(...) or spread syntax [...set]), or track seen keys in a Set / Map when deduplicating whole objects or building custom unique value lists. Using a Set gives clean O(n) average-time deduplication for primitives while avoiding nested .some() or .indexOf() scans on large arrays.


1. Extracting Unique Values for a Single Property with Set

When you want distinct values of a specific property (such as unique role, category, or tag values across records), filter out nullish/missing entries if needed, map to the property, and deduplicate with new Set(...):

// Extract unique non-nullish values for a given property from an array of objects
function getUniquePropertyValues(items, propName) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  if (typeof propName !== "string" || propName.length === 0) {
    throw new TypeError("Expected propName to be a non-empty string.");
  }

  const uniqueSet = new Set();

  for (const item of items) {
    if (item !== null && typeof item === "object" && propName in item) {
      const val = item[propName];
      if (val !== undefined && val !== null) {
        uniqueSet.add(val);
      }
    }
  }

  return Array.from(uniqueSet);
}

// Example usage:
const users = [
  { id: 1, name: "Alice", role: "admin" },
  { id: 2, name: "Bob", role: "editor" },
  { id: 3, name: "Cara", role: "admin" },
  { id: 4, name: "Dan", role: "viewer" }
];

console.log(getUniquePropertyValues(users, "role")); // ["admin", "editor", "viewer"]
  • Same-Value-Zero equality: Set deduplicates primitives reliably (including NaN), while treating distinct object references {} as separate entries.
  • Guard against null / non-objects: Checking item !== null && typeof item === "object" prevents TypeErrors on malformed array entries.

2. Deduplicating Objects by a Unique Key (e.g., id or Composite Key)

When you want distinct object records—or distinct derived/composite values such as "department:role"—track seen keys in a Set so the first (or latest) matching entry is preserved cleanly:

// Keep distinct objects based on a key selector function (preserving first occurrence)
function getUniqueObjectsBy(items, keySelector) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  if (typeof keySelector !== "function") {
    throw new TypeError("Expected keySelector to be a function.");
  }

  const seenKeys = new Set();
  const uniqueItems = [];

  for (const item of items) {
    const key = keySelector(item);
    if (!seenKeys.has(key)) {
      seenKeys.add(key);
      uniqueItems.push(item);
    }
  }

  return uniqueItems;
}

// Example usage:
const orders = [
  { id: "ord-1", region: "PK", total: 1200 },
  { id: "ord-2", region: "PK", total: 2500 },
  { id: "ord-1", region: "PK", total: 1200 }
];

console.log(getUniqueObjectsBy(orders, (order) => order.id));
// [{ id: "ord-1", region: "PK", total: 1200 }, { id: "ord-2", region: "PK", total: 2500 }]
  • Flexible key selection: A key selector function handles single fields (item.id), normalized strings (item.email.trim().toLowerCase()), or composite keys (${item.country}-${item.city}).
  • Preserves original order: Iterating once with Set.prototype.has() maintains first-seen order without mutating the source array.

3. Extracting Unique Values When Object Properties Hold Arrays

If each object contains an array field (such as tags: ["js", "dom"]) and you want a flat list of distinct values across all objects, flatten or iterate nested elements into a Set:

// Extract unique values across an array property on each object
function getUniqueFlattenedValues(items, arrayPropName) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  if (typeof arrayPropName !== "string" || arrayPropName.length === 0) {
    throw new TypeError("Expected arrayPropName to be a non-empty string.");
  }

  const uniqueValues = new Set();

  for (const item of items) {
    if (item !== null && typeof item === "object" && Array.isArray(item[arrayPropName])) {
      for (const entry of item[arrayPropName]) {
        if (entry !== undefined && entry !== null) {
          uniqueValues.add(entry);
        }
      }
    }
  }

  return Array.from(uniqueValues);
}

// Example usage:
const posts = [
  { title: "Post A", tags: ["javascript", "arrays"] },
  { title: "Post B", tags: ["arrays", "performance"] }
];

console.log(getUniqueFlattenedValues(posts, "tags")); // ["javascript", "arrays", "performance"]
  • Avoids intermediate array bloat: Adding directly into a Set inside nested loops works well even across large collections.
  • Validate nested arrays: Checking Array.isArray(item[arrayPropName]) safely skips items with missing or non-array fields.

TL;DR: Extract distinct property values from an array of objects using Array.from(new Set(items.map(obj => obj.prop))) (with null/object guards), or deduplicate objects and composite values in O(n) time using a Set of selected keys.