require-array-sort-compare
Require
Array#sort
calls to always provide acompareFunction
.
This rule requires type information to run.
When called without a compare function, Array#sort()
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 Array#sort()
method that doesn't provide a compare
argument.
module.exports = {
"rules": {
"@typescript-eslint/require-array-sort-compare": "warn"
}
};
Examples
This rule aims to ensure all calls of the native Array#sort
method provide a compareFunction
, while ignoring calls to user-defined sort
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 an options object with the following properties:
interface Options {
/**
* Whether to ignore arrays in which all elements are strings.
*/
ignoreStringArrays?: boolean;
}
const defaultOptions: Options = [{ ignoreStringArrays: false }];
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();
const one = '1';
const two = '2';
const three = '3';
[one, two, three].sort();
When Not To Use It
If you understand the language specification enough, and/or only ever sort arrays in a string-like manner, you can turn this rule off safely.