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:
[lint.rules]
"unicorn/no-array-sort" = "error" # or "warn"
Every option, set to its default:
[lint.rules]
"unicorn/no-array-sort" = ["error", {
allowExpressionStatement = true,
allowAfterSpread = false,
}]
Examples
Reported:
const ranked = players.sort((a, b) => b.score - a.score);
Copying the array first is reported too, because toSorted() already makes a copy:
const ranked = [...players].sort((a, b) => b.score - a.score);
Not reported:
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:
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:
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(). |
players.sort((a, b) => b.score - a.score);
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.