Skip to content

Latest commit

Β 

History

History
60 lines (40 loc) Β· 1.57 KB

File metadata and controls

60 lines (40 loc) Β· 1.57 KB

Prefer Array#toSorted() over Array#sort()

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

Prefer using Array#toSorted() over Array#sort().

Array#sort() modifies the original array, while Array#toSorted() returns a new sorted array.

Examples

// ❌
const sorted = [...array].sort();

// βœ…
const sorted = array.toSorted();
// ❌
const sorted = [...iterable].sort();

// βœ…
const sorted = [...iterable].toSorted();
// ❌
const sorted = [...array].sort((a, b) => a - b);

// βœ…
const sorted = array.toSorted((a, b) => a - b);

Options

Type: object

allowExpressionStatement

Type: boolean
Default: true

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

/* eslint unicorn/no-array-sort: ["error", {"allowExpressionStatement": false}] */
// ❌
array.sort();

Related rules