useArraySortCompare
Summary
Section titled “Summary”- Rule available since:
v2.3.5 - Diagnostic Category:
lint/nursery/useArraySortCompare - This rule doesn’t have a fix.
- The default severity of this rule is information.
- This rule belongs to the following domains:
- Sources:
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "useArraySortCompare": "error" } } }}Description
Section titled “Description”Require Array#sort and Array#toSorted calls to always provide a compareFunction.
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.
Examples
Section titled “Examples”Invalid
Section titled “Invalid”const array: any[] = [];array.sort();/invalid.ts:2:1 lint/nursery/useArraySortCompare ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Compare function missing.
1 │ const array: any[] = [];
> 2 │ array.sort();
│ ^^^^^^^^^^^^
3 │
ℹ 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.
ℹ Add a compare function to prevent unexpected sorting.
const array: any[] = [];array.sort((a, b) => a - b);Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.