require-array-sort-compare
Require
Array#sort
andArray#toSorted
calls 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.
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();
Open in Playgroundconst array: any[];
const userDefinedType: { sort(): void };
array.sort((a, b) => a - b);
array.sort((a, b) => a.localeCompare(b));
userDefinedType.sort();
Open in PlaygroundOptions
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
Examples of code for this rule with { ignoreStringArrays: true }
:
- ❌ Incorrect
- ✅ Correct
const one = 1;
const two = 2;
const three = 3;
[one, two, three].sort();
Open in Playgroundconst one = '1';
const two = '2';
const three = '3';
[one, two, three].sort();
Open in PlaygroundWhen 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 Performance Troubleshooting if you experience performance degredations after enabling type checked rules.