@typescript-eslint/eslint-plugin has an existing rule @typescript-eslint/require-array-sort-compare. See that rule doc for why omitting a comparator leads to common bugs (in both JavaScript and TypeScript).
Because TypeScript provides type information to the rule, the typescript-eslint rule can reliably operate only on actual arrays. But that also means anyone using plain JavaScript code (i.e. without TypeScript/typescript-eslint) cannot benefit from the rule.
We could create a version of this rule that does not depend on type information and that would be targeted at JavaScript users. It could simply look for calls like myArray.sort()
, similar to many of our existing rules like unicorn/require-array-join-separator.
If we run into unacceptably-high false positives, we could try to add heuristics for detecting when a variable is likely to be or not to be an array (e.g. ignoring common classes/objects that have a sort()
function but are known to not be an array) (I implemented a bunch of related heuristics in ember/no-array-prototype-extensions). With static analysis from eslint-utils, we can also check to see if a variable's definition is visible to us or has a static value for determining if it's an array, but this is only helpful in limited situations.
We could name this rule require-array-sort-compare
.
We could add suggestions to the rule for common comparator functions (e.g. (a, b) => a.localeCompare(b)
for strings).
Related:
array.sort();
array.sort((a, b) => a - b);
array.sort((a, b) => a.localeCompare(b));
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too