To sort an array in descending order in JavaScript, you can use the `sort` method along with a custom comparison function that sorts elements in descending order.
In this example,
numbers
.sort
method with a custom comparison function to sort the array of numbers in descending order.let numbers = [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 = ["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 JavaScript language with well detailed examples.