unicorn/no-array-sort Suspicious
What it does
Prefer using Array#toSorted() over Array#sort().
Why is this bad?
Array#sort() modifies the original array in place, which can lead to unintended side effects—especially when the original array is used elsewhere in the code.
Examples
Examples of incorrect code for this rule:
const sorted = [...array].sort();Examples of correct code for this rule:
const sorted = [...array].toSorted();Configuration
This rule accepts a configuration object with the following properties:
allowAfterSpread
type: boolean
default: false
When set to true, allows sorting a fresh array created by a spread, e.g. [...iterable].sort(). This avoids the double allocation of toSorted() when sorting an iterable such as a Set.
Example of correct code for this rule with allowAfterSpread set to true:
const sorted = [...mySet].sort();allowExpressionStatement
type: boolean
default: true
When set to true (default), allows array.sort() as an expression statement. Set to false to forbid Array#sort() even if it's an expression statement.
Example of incorrect code for this rule with allowExpressionStatement set to false:
array.sort();How to use
To enable this rule using the config file or in the CLI, you can use:
{
"rules": {
"unicorn/no-array-sort": "error"
}
}import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/no-array-sort": "error",
},
});oxlint --deny unicorn/no-array-sortVersion
This rule was added in v1.15.0.
