To sort an array in descending order in TypeScript, you can follow the same approach as JavaScript by using the `sort` method along with a custom comparison function.
In this example,
numbers
.sort
method with a custom comparison function to sort the array of numbers in descending order.let numbers: number[] = [5, 2, 8, 1, 9];
numbers.sort((a, b) => b - a);
console.log(numbers);
[ 9, 8, 5, 2, 1 ]
In this example,
words
.sort
method with a custom comparison function to sort the array of strings in descending order.let words: string[] = ["apple", "banana", "cherry", "date"];
words.sort((a, b) => b.localeCompare(a));
console.log(words);
[ 'date', 'cherry', 'banana', 'apple' ]
In this tutorial, we learned How to Sort an Array in Descending Order in TypeScript language with well detailed examples.