Skip to main content

uniq

Returns a new array with duplicate elements removed, containing only unique elements.

By default, duplicate detection is performed only for primitive values. If the second argument iteratee function is provided, duplicate detection is based on the iteratee return value for each element.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)

Default

NamehzmeanPerformance
modern-kit/uniq9,049,882.240.0001fastest
lodash/uniq6,259,278.140.0002slowest
  • modern-kit/uniq
    • 1.45x faster than lodash/uniq

with iteratee

NamehzmeanPerformance
modern-kit/uniq10,429,151.370.0001fastest
lodash/uniqBy4,837,704.040.0002slowest
  • modern-kit/uniq
    • 2.16x faster than lodash/uniqBy

Interface

typescript
function uniq<T>(arr: T[] | readonly T[]): T[];

function uniq<T, U = T>(
arr: T[] | readonly T[],
iteratee?: (item: T) => U
): T[];

Usage

Basic Usage

typescript
import { uniq } from '@modern-kit/utils';

uniq([1, 2, 3]); // [1, 2, 3]
uniq([1, 2, 2, 2, 3]); // [1, 2, 3]

Iteratee Usage

typescript
import { uniq } from '@modern-kit/utils';

const testArr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
{ id: 3, name: 'gromit' },
{ id: 3, name: 'gromit' },
];

uniq(testArr, (item) => item.id);
/*
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'gromit' }
];
*/

uniq([1, 2, 2.1, 2.2, 2.3, 3], (item) => Math.floor(item)); // [1, 2, 3]