Skip to content

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:

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

Examples of correct code for this rule:

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

Configuration

This rule accepts a configuration object with the following properties:

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:

js
array.sort();

How to use

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

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

References