π 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.
// β - 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.