Skip to content

unicorn/no-array-sort Suspicious ​

🛠️ An auto-fix is available for this rule.

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:

js
const sorted = [...array].sort();

Examples of correct code for this rule:

js
const sorted = [...array].toSorted();

Options ​

allowExpressionStatement ​

{ type: boolean, default: true }

This rule allows array.sort() as an expression statement by default, Pass allowExpressionStatement: false to forbid Array#sort() even if it's an expression statement.

Examples of incorrect code for this rule with the { "allowExpressionStatement": false } option:

js
array.sort();

How to use ​

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny unicorn/no-array-sort
json
{
  "rules": {
    "unicorn/no-array-sort": "error"
  }
}

References ​

Released under the MIT License.