You can use the sort() method to sorts the values as strings in alphabetical and descending order in JavaScript. By default this method sorts values in ascending order.
Note: This method changes the original array.
Example of Sort Array in descending order JavaScript
HTML Example code Sort numbers in an array in descending order:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <head> <script type="text/javascript"> <script type="text/javascript"> var ab = [40, 30, 10, 50, 20, 60]; ab.sort(function(a, b){return b-a}); alert(ab); </script> </script> </head> <body> </body> </html> |
Output:

What is a way to sort strings in descending order in JavaScript?
Answer: There a many ways to sort string in JavaScript, we are trying only with 3 most common ways:-
1 |
obj.sort().reverse(); |
Or
1 |
obj.sort((a, b) => (a > b ? -1 : 1)) |
Or
1 |
obj.sort((a, b) => b.localeCompare(a) ) |
The performance winner is : obj.sort().reverse()
.
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
).
Performance test here :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html> <head> <script type="text/javascript"> var results = [[],[],[]] for(let i = 0; i < 100; i++){ const randomArrayGen = () => Array.from({length: 10000}, () => Math.random().toString(30)); const randomArray = randomArrayGen(); const copyArray = x => x.slice(); obj = copyArray(randomArray); let t0 = performance.now(); obj.sort().reverse(); let t1 = performance.now(); obj = copyArray(randomArray); let t2 = performance.now(); obj.sort((a, b) => (a > b ? -1 : 1)) let t3 = performance.now(); obj = copyArray(randomArray); let t4 = performance.now(); obj.sort((a, b) => b.localeCompare(a)) let t5 = performance.now(); results[0].push(t1 - t0); results[1].push(t3 - t2); results[2].push(t5 - t4); } const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ; console.log("obj.sort().reverse(): " + calculateAverage(results[0])); console.log("obj.sort((a, b) => (a > b ? -1 : 1)): " + calculateAverage(results[1])); console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results[2])); </script> </head> <body> </body> </html> |
Output:

Source: stackoverflow…
Do comment if you know much better example or have any doubts on this topic.
Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version