跳转到内容

useArraySortCompare

此内容尚不支持你的语言。

biome.json
{
"linter": {
"rules": {
"nursery": {
"useArraySortCompare": "error"
}
}
}
}

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:

example.ts
[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.

invalid.ts
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.

valid.ts
const array: any[] = [];
array.sort((a, b) => a - b);