Use the JavaScript sort() method with the reverse() method in the Array object to get sort elements in descending. This method sorts the elements of an array and overwrites the original array.
obj.sort().reverse();
The reverse()
method reverses the order of the elements in an array and overwrites the original array.
JavaScript sort descending example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort().reverse();
console.log(fruits)
var arr = ["a","b","c","A","B","Z"];
arr.sort((a, b) => b.localeCompare(a));
console.log(arr)
let num = [0, 1 , 2, 3, 10, 20, 30 ];
num.sort().sort((a, b) => b - a);
console.log(num);
</script>
</body>
</html>
Output:
Other methods
Using the sort compare function
obj.sort((a, b) => (a > b ? -1 : 1))
Using localeCompare
obj.sort((a, b) => b.localeCompare(a) )
The performance
Testing with an array of 10.000 elements, obj.sort().reverse()
is faster than obj.sort( function )
(except on chrome), and obj.sort( function )
(using localCompare
).
Source: stackoverflow.com/
Comment if you have any doubts or suggestions on this Js sorting topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version