TypeScript Array sort() Method
The sort() method in TypeScript sorts the elements of an array and returns the sorted array. By default, it sorts an array in ascending order. It can take an optional compareFunction to define the sort order, allowing for custom sorting logic.
Syntax
array.sort( compareFunction )
Parameter: This method accepts a single parameter as mentioned above and described below:
- compareFunction : This parameter is the function that defines the sort order
Return Value: This method returns the sorted array.
The below example illustrates the Array sort() method in TypeScriptJS:
Example 1: Sorting Numbers
In this example we initializes an array arr with numbers, uses the sort() method to sort the array in ascending order
let arr: number[] = [11, 23, 7, 89, 98];
arr.sort((a, b) => a - b);
console.log(arr);
Output:
[7, 11, 23, 89, 98]
Example 2: Sorting Characters
In this example we initializes an array chars with characters, sorts the array in ascending alphabetical order using the sort() method.
let chars: string[] = ['G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'];
chars.sort();
console.log(chars);
Output:
["G", "G", "e", "e", "e", "e", "f", "k", "k", "o", "r", "s", "s"]