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:
Table of Content
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.
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.
const fruits: string[] = [ "Apple" , "Orange" , "Banana" , "Mango" ];
fruits.sort(); console.log( "Sorted Fruits: " , fruits);
|
Output:
Sorted Fruits: [ 'Apple', 'Banana', 'Mango', 'Orange' ]
Sorting Array of Objects
Example: In this example, we have an array of people with name
and age
properties. We use the sort
method with a custom comparison function to sort the array based on the age
property in ascending order.
interface Person { name: string;
age: number;
} const people: Person[] = [ { name: "Alice" , age: 25 },
{ name: "Bob" , age: 30 },
{ name: "Charlie" , age: 22 },
{ name: "David" , age: 28 }
]; people.sort((a, b) => a.age - b.age); console.log( "Sorted People by Age: " , people);
|
Output:
Sorted People by Age: [
{ name: 'Charlie', age: 22 },
{ name: 'Alice', age: 25 },
{ name: 'David', age: 28 },
{ name: 'Bob', age: 30 }
]