Skip to main content

uniqWith()

uniqWith(str, comparator): string

Creates a duplicate-free version of a string using a custom comparator.

๐Ÿ’Ž Why is this a Hidden Gem?

No native equivalent for character-level deduplication with custom logic. Useful for case-insensitive or locale-aware uniqueness.

note

Keeps first occurrence of each character. O(nยฒ) complexity.


Parametersโ€‹

str: stringโ€‹

The string to process.

comparator: (a, b) => booleanโ€‹

Function to compare characters for equality.


Returns: stringโ€‹

The string with unique characters (first occurrence kept).


Sinceโ€‹

2.0.0


Performanceโ€‹

O(nยฒ) time, O(n) space where n is string length. Uses every() for each character check.


Also known asโ€‹

dedupeWith (Effect) ยท uniqWith (Lodash, es-toolkit, Remeda, Ramda) ยท unique (Radashi) ยท โŒ (Modern Dash, Antfu)


Exampleโ€‹

uniqWith('hello', (a, b) => a === b);
// => 'helo'

uniqWith('Hello', (a, b) => a.toLowerCase() === b.toLowerCase());
// => 'Helo'

uniqWith('hello world', (a, b) => /\s/.test(a) && /\s/.test(b));
// => 'hello world'

How it works?โ€‹

Creates a duplicate-free version of a string using a custom comparator.

Example: Case-insensitiveโ€‹

Comparator Examplesโ€‹

ComparatorInputOutput
(a, b) => a === b'hello''helo'
(a, b) => a.toLowerCase() === b.toLowerCase()'Hello''Helo'
(a, b) => /\s/.test(a) && /\s/.test(b)'a b c''a b c'

Performanceโ€‹

O(nยฒ) time complexity due to every() check for each character.


Use Casesโ€‹

Filter unique characters ๐Ÿ“Œโ€‹

Remove duplicate characters based on custom logic (e.g., case-insensitive). Useful for generating unique sets of symbols or cleaning input.

const unique = uniqWith('aAaB', (a, b) => a.toLowerCase() === b.toLowerCase());
// 'aB'

Remove consecutive duplicatesโ€‹

Filter out repeated characters while preserving first occurrence.

const clean = uniqWith('aaabbbccc', (a, b) => a === b);
// 'abc'