uniqueDeep
Removes deeply equal duplicate values from an array.
1/**
2 * Removes deeply equal duplicate values from an array.
3 *
4 * @param arr - The array of items.
5 * @returns A new array with deeply equal duplicates removed.
6 */
7export function uniqueDeep<T>(arr: T[]): T[] {
8 return arr.filter((item, index) => {
9 return (
10 arr.findIndex(other => deepEqual(item, other)) === index
11 );
12 });
13}
Supports deep equality
Unlike
Set
or shallow comparison methods, this utility removes duplicates by comparing nested structures, such as objects and arrays, usingdeepEqual
.Preserves first occurrence
Retains the first unique match and removes later duplicates, which is often desirable in list deduplication.
Immutable by design
Returns a new array, keeping the original array unchanged — important for safe usage in functional or reactive contexts.
Handles mixed-type arrays
Works with arrays containing objects, arrays, and primitives, offering broad applicability.
Reuses logic through
deepEqual
Can integrate with a custom or optimized deep equality function, which makes the utility adaptable to various project needs.
Tests | Examples
1test('uniqueDeep - removes duplicate primitives', () => {
2 expect(uniqueDeep([1, 2, 2, 3])).toEqual([1, 2, 3]);
3});
4
5test('uniqueDeep - removes duplicate objects', () => {
6 const input = [{ id: 1 }, { id: 2 }, { id: 1 }];
7 expect(uniqueDeep(input)).toEqual([{ id: 1 }, { id: 2 }]);
8});
9
10test('uniqueDeep - removes deeply equal nested arrays', () => {
11 const input = [[1, 2], [1, 2], [2, 3]];
12 expect(uniqueDeep(input)).toEqual([[1, 2], [2, 3]]);
13});
14
15test('uniqueDeep - handles empty array', () => {
16 expect(uniqueDeep([])).toEqual([]);
17});
18
19test('uniqueDeep - all items are unique', () => {
20 const items = [{ a: 1 }, { a: 2 }, { a: 3 }];
21 expect(uniqueDeep(items)).toEqual(items);
22});
Common Use Cases
Cleaning up form or survey submissions
When a user submits repeating nested data, like duplicated address objects or multiple-choice selections with metadata.
Normalizing external API responses
Useful when working with third-party APIs that may return redundant entries with identical nested data.
Deduplicating configuration or metadata arrays
Often used in build tools, CMS data, or UI component props where deeply nested structures are reused.
Merging and cleaning datasets
When combining data from multiple sources (e.g., importing JSON records), this function ensures structural uniqueness across the dataset.