Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

unique

Removes duplicate primitive values from an array.

TypeScript
Copied!
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, and symbol, 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

TypeScript
Copied!
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.

Codebase: Utilities -> Arrays -> unique | Yevhen Klymentiev