Back to Snippets
CODE

Array Deduplication (Object/Array Support)

Description

Supports deduplication of not only primitive types but also complex types like objects and arrays, using JSON.stringify to generate unique identifiers

Code

/**
 * Array deduplication (supports primitive + reference types)
 * @param arr Array to be deduplicated
 * @returns New deduplicated array
 */
function uniqueArray<T>(arr: T[]): T[] {
  const cache = new Set<string>();
  return arr.filter(item => {
    const key = JSON.stringify(item);
    if (cache.has(key)) return false;
    cache.add(key);
    return true;
  });
}

// Usage Example
const arr = [1, 2, 2, { a: 1 }, { a: 1 }, [1], [1]];
console.log(uniqueArray(arr)); // [1, 2, { a: 1 }, [1]]

Usage

Great for deduplicating API response data, list data, or arrays containing objects/arrays

Tags

Array ManipulationDeduplicationComplex Types