Skip to content

arrayMutableSorts

Reports .sort() calls on arrays that mutate the original array.

✅ This rule is included in the ts stylistic and stylisticStrict presets.

The .sort() method mutates the original array in place. Using .toSorted() instead returns a new sorted array without modifying the original, making code more predictable and avoiding unintended side effects.

const
const values: number[]
values
= [3, 1, 2];
const
const sorted: number[]
sorted
=
const values: number[]
values
.
Array<number>.sort(compareFn?: ((a: number, b: number) => number) | undefined): number[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

@param

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11,2,22,1].sort((a, b) => a - b)

sort
();
const
const items: number[]
items
= [3, 1, 2];
const
const sorted: number[]
sorted
=
const items: number[]
items
.
Array<number>.sort(compareFn?: ((a: number, b: number) => number) | undefined): number[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

@param

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11,2,22,1].sort((a, b) => a - b)

sort
((
a: number
a
,
b: number
b
) =>
a: number
a
-
b: number
b
);
const
const data: number[]
data
= [3, 1, 2];
const
const result: number[]
result
= [...
const data: number[]
data
].
Array<number>.sort(compareFn?: ((a: number, b: number) => number) | undefined): number[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

@param

compareFn Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.

[11,2,22,1].sort((a, b) => a - b)

sort
();

This rule is not configurable.

If you intentionally want to mutate the original array in place, or if you’re working in an environment that doesn’t support .toSorted() (ES2023+), you may want to disable this rule. Note that .sort() is still allowed when used as a standalone expression statement since the mutation is likely intentional in that case.

Made with ❤️‍🔥 around the world by the Flint team and contributors.