The sort()
method in TypeScript sorts the elements for an array and returns the sorted array. By default, it sorts an array in ascending order.
array.sort() array.sort(function)
array
: This is the array that we want to sort.function
: This is the function we want to use to specify the sort order.The value returned is a sorted array.
// create arrays in TypeScript let names: string[] = ["Theodore", "James", "Peter", "Amaka"] let numbers : Array<number>; numbers = [12, 34, 5, 0.9] let cars : Array<string> = ["Porsche", "Toyota", "Lexus"] let randomValues : Array<string | number | boolean> = ["one",1, "two", 2, 56, true] // sort the arrays console.log(names.sort()) console.log(numbers.sort()) console.log(cars.sort()) console.log(randomValues.sort())
sort()
method, we sort the arrays and print the results to the console screen.// create an array let numbers = [12, 34, 5, 0.9] // sort the array using a function numbers.sort(function(a, b){ return b - a; // sort in descending order }) // print sorted array console.log(numbers)
sort()
method, with a function to sort the array in descending order. RELATED TAGS
CONTRIBUTOR
View all Courses