Custom Sorting Function
We can define a custom sorting function based on our specific criteria and use it with the sort method. This method is useful when sorting complex data structures or when a custom sorting logic is required.
Example: Sorting the detail of person using defined custom sorting function based upon our requirement.
let detail: { name: string; age: number }[] = [
{ name: "ABC", age: 30 },
{ name: "XYZ", age: 25 },
{ name: "MNP", age: 35 },
];
// Sort by age in ascending order
detail.sort((a, b) => a.age - b.age);
console.log(detail);
Output:
[
{ name: 'XYZ', age: 25 },
{ name: 'ABC', age: 30 },
{ name: 'MNP', age: 35 }
]
How to Sort an Array in TypeScript ?
Array sorting is the process of arranging the elements within an array in a specified order, often either ascending or descending based on predetermined criteria.
Below are the approaches used to sort an array in typescript:
Table of Content
- Method 1: Using sort method
- Method 2: Spread Operator
- Method 3: Custom Sorting Function
- Method 4: Using a Priority Queue for Custom Sort Order