How to Sort an Array in TypeScript ?
Last Updated :
13 Feb, 2024
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:
Method 1: Using sort method
The sort method is a built-in array method in TypeScript that sorts the elements of an array in place. It takes a compare function as an argument, allowing you to define custom sorting criteria.
Example: Sorting an array in ascending and descending order using the sort function.
Javascript
let numbers: number[] = [4, 2, 7, 1, 9];
numbers.sort((a, b) => a - b);
console.log( "Ascending: " + numbers);
numbers.sort((a, b) => b - a);
console.log( "Descending: " + numbers);
|
Output:
Ascending: 1,2,4,7,9
Descending: 9,7,4,2,1
Method 2: Spread Operator
This method involves creating a copy of the array using the spread operator (…) and then using array methods like sort. This approach keeps the original array unchanged and produces a new sorted array.
Example: Sorting an array in ascending and descending order using the sort with help of spread operator to keep the original array unchanged.
Javascript
let numbers: number[] = [4, 2, 7, 1, 9];
let sortedAscending = [...numbers].sort((a, b) => a - b);
console.log( "Ascending: " + sortedAscending);
let sortedDescending = [...numbers].sort((a, b) => b - a);
console.log( "Descending: " + sortedDescending);
|
Output:
Ascending: 1,2,4,7,9
Descending: 9,7,4,2,1
Method 3: 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.
Javascript
let detail: { name: string; age: number }[] = [
{ name: "ABC" , age: 30 },
{ name: "XYZ" , age: 25 },
{ name: "MNP" , age: 35 },
];
detail.sort((a, b) => a.age - b.age);
console.log(detail);
|
Output:
[
{ name: 'XYZ', age: 25 },
{ name: 'ABC', age: 30 },
{ name: 'MNP', age: 35 }
]
Share your thoughts in the comments
Please Login to comment...