require-array-sort-compare
Require
Array#sortandArray#toSortedcalls to always provide acompareFunction.
💭
This rule requires type information to run, which comes with performance tradeoffs.
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
eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/require-array-sort-compare": "error"
}
});
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/require-array-sort-compare": "error"
}
};
Try this rule in the playground ↗