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'