Aller au contenu principal

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.

remarque

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'