unicorn/no-array-sort

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

has suggestions

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.

Configure#

Off by default. To turn it on:

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

Every option, set to its default:

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

Examples#

example.js1 problem
const ranked = players.sort((a, b) => b.score - a.score);

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

example.js1 problem
const ranked = [...players].sort((a, b) => b.score - a.score);
example.jsNo problems
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:

example.jsNo problems
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:

example.jsNo problems
const recent = await db.posts.find().sort({ createdAt: -1 });

Options#

OptionDefaultWhat it does
allowExpressionStatementtrueAllow array.sort(); as a standalone statement.
allowAfterSpreadfalseAllow [...array].sort().
example.jswith { "allowExpressionStatement": false }1 problem
players.sort((a, b) => b.score - a.score);
example.jswith { "allowAfterSpread": true }No problems
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.