TypeScript Sorting Array
Last Updated :
24 Apr, 2025
To sort an array in TypeScript we could use Array.sort() function. The Array.sort() is an inbuilt TypeScript function that is used to sort the elements of an array.
Syntax:
array.sort(compareFunction)
Below are the places where we could use the sort() function:
Sorting Array of Numbers
Example: In this example, we have an array of numbers, and we use the sort
method with a custom comparison function to sort the array in ascending order.
JavaScript
const numbers: number[] = [4, 2, 7, 1, 9, 5];
numbers.sort((a, b) => a - b);
console.log("Sorted Numbers: ", numbers);
Output:
Sorted Numbers: [1, 2, 4, 5, 7, 9]
Sorting Array of Strings
Example: In this example, we have an array of strings, and we use the sort
method to sort the strings in default lexicographic order.
JavaScript
const fruits: string[] = ["Apple", "Orange", "Banana", "Mango"];
fruits.sort();
console.log("Sorted Fruits: ", fruits);