Open In App

TypeScript Sorting Array

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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);


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.

Javascript




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 }
]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads