Skip to content

Latest commit

Β 

History

History
57 lines (42 loc) Β· 2.34 KB

File metadata and controls

57 lines (42 loc) Β· 2.34 KB

require-array-sort-compare

πŸ“ Require a compare function when calling Array#sort() or Array#toSorted().

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

Without an explicit compare function, Array#sort() and Array#toSorted() sort elements by converting them to strings, which produces unexpected results for numbers and other non-string values.

A typed array is never reported, because TypedArray#sort() already sorts numerically. Most array rules do report a typed array receiver, since it shares Array's method surface.

Examples

// ❌ - Sorts as strings: [1, 10, 2, 20, 3]
const numbers = [3, 1, 10, 2, 20];
numbers.toSorted();

// βœ… - Properly numeric sort: [1, 2, 3, 10, 20]
const numbers = [3, 1, 10, 2, 20];
numbers.toSorted((a, b) => a - b);
// ❌ - String sorting on numbers is wrong
[5, 10, 15, 2, 25].sort();
// β†’ [10, 15, 2, 25, 5] (unexpected!)

// βœ…
[5, 10, 15, 2, 25].sort((a, b) => a - b);
// β†’ [2, 5, 10, 15, 25]
// ❌ - Sorting strings without explicit compare
const names = ['Alice', 'bob', 'Charlie'];
names.sort();
// β†’ ['Alice', 'Charlie', 'bob'] (case-sensitive)

// βœ… - Case-insensitive sorting
const names = ['Alice', 'bob', 'Charlie'];
names.sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}));
// β†’ ['Alice', 'bob', 'Charlie']
// βœ… - Descending order
const numbers = [3, 1, 4, 1, 5, 9];
numbers.sort((a, b) => b - a); // [9, 5, 4, 3, 1, 1]

Tip

If you use typed linting, the @typescript-eslint/require-array-sort-compare rule is type-aware and can be more accurate.