In TypeScript, we use the sort()
method for sorting an array. This means that we want the elements of an array to be displayed in either ascending or descending order using number values and string values.
The syntax for the sort()
method is given below:
array.sort(compareFunction)
compareFunction
: This is an optional function that defines how elements should be sorted.
Elements are returned in a lexicographical way.
Here are some example use cases of the sort()
method.
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let numbers : Array<number>;numbers = [12, 34, 5, 0.9]let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]// sort the arrays and print resultsconsole.log(names.sort())console.log(numbers.sort())console.log(cars.sort())