Skip to main content

castComparator()

castComparator<Item, Key>(key, options?): (a, b) => number

castComparator<Item, MappedValue>(mapper, options?): (a, b) => number

Creates a comparator function for Array.sort() with flexible mapping and comparison options.

note

Null/undefined values sort last. Dates compare by timestamp. Uses localeCompare for strings.


Type Parameters​

Item: Item​

The type of items being sorted.

Key: Key extends string | number | symbol​

The type of the property key.

MappedValue: MappedValue​

The type of the mapped value.


Parameters​

Overload 1:

key: Key​

options?: ComparatorOptions<Item[Key]>​

Comparison options.

Overload 2:

mapper: (item) => MappedValue​

options?: ComparatorOptions<MappedValue>​

Comparison options.


Returns: (a, b): number​

A comparator function for Array.sort().

a: Item
b: Item
Returns: number


Since​

2.0.0


Also known as​

castComparator (Radashi) · comparator (Ramda) · ❌ (Lodash, es-toolkit, Remeda, Effect, Modern Dash, Antfu)


Example​

const users = [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }];

users.sort(castComparator('age'));
// Sorted by age ascending

users.sort(castComparator((u) => u.name.length));
// Sorted by name length

users.sort(castComparator('age', { reverse: true }));
// Sorted by age descending

How it works?​

Creates a comparator function for Array.sort() from a property key or mapper function.

Property Key vs Mapper Function​

Options​

Default Comparison​

TypeComparison
numberNumeric subtraction
stringlocaleCompare
DateTimestamp comparison
null/undefinedSorted last

Use Cases​

Sort arrays by property πŸ“Œβ€‹

Create reusable comparators for Array.sort() with property names. Essential for clean, readable sorting code.

const users = [
{ name: "John", age: 25 },
{ name: "Jane", age: 30 }
];

users.sort(castComparator("age"));
// [{ name: "John", age: 25 }, { name: "Jane", age: 30 }]

Sort arrays by computed values​

Sort by computed values, custom comparison functions, and reverse order. Essential for complex sorting requirements.

const files = ["report.pdf", "image.png", "data.json"];

// Sort by extension length
files.sort(castComparator((f) => f.split(".").pop()?.length));

Sort in reverse order​

Sort arrays in descending order with simple parameter. Essential for common reverse sorting needs.

users.sort(castComparator("age", { reverse: true }));
// [{ name: "Jane", age: 30 }, { name: "John", age: 25 }]

ComparatorOptions<ComparedValue>​

Interface

Options for the comparator function.


Since​

2.0.0


Type Parameters​

ComparedValue: ComparedValue​

The type of values being compared.


Properties​

compare()?: (a, b) => number​

Custom comparison function.

a: ComparedValue
b: ComparedValue
Returns: number

reverse?: boolean​

If true, reverses the sort order.