unique
Removes duplicate primitive values from an array.
1/**
2 * Removes duplicate primitive values from an array.
3 *
4 * @param arr - The input array of primitive values.
5 * @returns A new array containing only unique values.
6 */
7export function unique<T>(arr: T[]): T[] {
8 return Array.from(new Set(arr));
9}
Efficient duplicate removal using
Set
Utilizes JavaScript's
Set
, which inherently enforces uniqueness, making the implementation both concise and performant.Linear time complexity
O(n)
The use of
Set
avoids nested iterations, offering significantly better performance than methods like.includes()
or.indexOf()
.Minimalistic and highly readable
The function is extremely concise, making it easy to understand and maintain.
Supports all primitive types
Works correctly with numbers, strings, booleans,
null
,undefined
, andsymbol
, including mixed-type arrays such as[1, '1', true]
.Immutable by design
Returns a new array, preserving the original input. This is important for functional programming patterns and React state management.
Tests | Examples
1test('unique - removes duplicate strings', () => {
2 expect(unique(['a', 'b', 'a', 'c'])).toEqual(['a', 'b', 'c']);
3});
4
5test('unique - returns same array when no duplicates', () => {
6 expect(unique([1, 2, 3])).toEqual([1, 2, 3]);
7});
8
9test('unique - works with empty array', () => {
10 expect(unique([])).toEqual([]);
11});
12
13test('unique - removes duplicate booleans', () => {
14 expect(unique([true, false, true])).toEqual([true, false]);
15});
16
17test('unique - removes duplicate mixed values', () => {
18 expect(unique([1, '1', 1])).toEqual([1, '1']);
19});
Common Use Cases
Deduplicating identifiers
Useful when aggregating data from different sources and ensuring IDs or keys are unique.
Cleaning user input
When users provide lists of items (tags, emails, filters), this utility can prevent duplicates from being stored or processed.
Normalizing API responses
Helps ensure data integrity by removing repeated values after merging responses from multiple endpoints.
Generating unique filter options
Commonly used to extract unique categories, tags, or types from data sets for UI filters or dropdowns.