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.
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.
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.
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 values:number[]
values = [3, 1, 2];
const
const sorted:any
sorted =
const values:number[]
values.toSorted();
Error ts(2550) ― Property 'toSorted' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2023' or later.
const
const items:number[]
items = [3, 1, 2];
const
const sorted:any
sorted =
const items:number[]
items.toSorted((
a: any
a,
b: any
b) =>
a: any
a -
b: any
b);
Error ts(2550) ― Property 'toSorted' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2023' or later.
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.
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.