require-array-sort-compare
Require
Array#sortandArray#toSortedcalls to always provide acompareFunction.
This rule requires type information to run.
When called without a compare function, Array#sort() and Array#toSorted() converts all non-undefined array elements into strings and then compares said strings based off their UTF-16 code units [ECMA specification].
The result is that elements are sorted alphabetically, regardless of their type. For example, when sorting numbers, this results in a "10 before 2" order:
[1, 2, 3, 10, 20, 30].sort(); //→ [1, 10, 2, 20, 3, 30]
This rule reports on any call to the sort methods that do not provide a compare argument.
- Flat Config
- Legacy Config
export default tseslint.config({
  rules: {
    "@typescript-eslint/require-array-sort-compare": "error"
  }
});
module.exports = {
  "rules": {
    "@typescript-eslint/require-array-sort-compare": "error"
  }
};
Try this rule in the playground ↗
Examples
This rule aims to ensure all calls of the native sort methods provide a compareFunction, while ignoring calls to user-defined methods.
- ❌ Incorrect
- ✅ Correct
const array: any[];
const stringArray: string[];
array.sort();
// String arrays should be sorted using `String#localeCompare`.
stringArray.sort();
const array: any[];
const userDefinedType: { sort(): void };
array.sort((a, b) => a - b);
array.sort((a, b) => a.localeCompare(b));
userDefinedType.sort();
Options
This rule accepts the following options:
type Options = [
  {
    /** Whether to ignore arrays in which all elements are strings. */
    ignoreStringArrays?: boolean;
  },
];
const defaultOptions: Options = [{ ignoreStringArrays: true }];
ignoreStringArrays
Whether to ignore arrays in which all elements are strings. Default: true.
Examples of code for this rule with { ignoreStringArrays: true }:
- ❌ Incorrect
- ✅ Correct
const one = 1;
const two = 2;
const three = 3;
[one, two, three].sort();
const one = '1';
const two = '2';
const three = '3';
[one, two, three].sort();
When Not To Use It
If you intentionally want your arrays to be always sorted in a string-like manner, you can turn this rule off safely.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.