# unicorn/no-array-sort

> Require `toSorted()` instead of `sort()`, which changes the array

`sort()` sorts the array in place and returns that same array. After `const ranked = players.sort(byScore)`, `players` is sorted too. `toSorted()` returns a new array and leaves the original alone.

`--fix-suggestions` replaces `sort` with `toSorted`.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/no-array-sort" = "error" # or "warn"
```

Every option, set to its default:

```toml bunfig.toml
[lint.rules]
"unicorn/no-array-sort" = ["error", {
  allowExpressionStatement = true,
  allowAfterSpread = false,
}]
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}
```js
const ranked = players.sort((a, b) => b.score - a.score);
```

Copying the array first is reported too, because `toSorted()` already makes a copy:

{/* bad */}
```js
const ranked = [...players].sort((a, b) => b.score - a.score);
```

Not reported:

{/* good */}
```js
const ranked = players.toSorted((a, b) => b.score - a.score);
```

A call used as a standalone statement is allowed by default. Nothing uses the result, so changing the array is the point:

{/* good */}
```js
players.sort((a, b) => b.score - a.score);
```

If the argument can't be a compare function, like an object or a string, `sort` belongs to something else, such as a database query:

{/* good */}
```js
const recent = await db.posts.find().sort({ createdAt: -1 });
```

## Options

| Option | Default | What it does |
| --- | --- | --- |
| `allowExpressionStatement` | `true` | Allow `array.sort();` as a standalone statement. |
| `allowAfterSpread` | `false` | Allow `[...array].sort()`. |

{/* bad {"options": [{"allowExpressionStatement": false}]} */}
```js
players.sort((a, b) => b.score - a.score);
```

{/* good {"options": [{"allowAfterSpread": true}]} */}
```js
const ranked = [...players].sort((a, b) => b.score - a.score);
```

## When not to use it

`toSorted()` is part of ES2023. Turn the rule off if your code needs to run somewhere that doesn't have it.
