Sort Array in descending order JavaScript | 3 Ways code

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:

<!DOCTYPE html>
<html>
<script type="text/javascript">
<script type="text/javascript">
var ab = [40, 30, 10, 50, 20, 60];
ab.sort(function(a, b){return b-a});

</script>
</script>

<body>

</body>
</html>

Output:

What are the ways 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:-

obj.sort().reverse();

Or

obj.sort((a, b) => (a > b ? -1 : 1))

Or

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 :

<!DOCTYPE html>
<html>
<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.push(t1 - t0);
results.push(t3 - t2);
results.push(t5 - t4);
}

const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ;

console.log("obj.sort().reverse():                   " + calculateAverage(results));
console.log("obj.sort((a, b) => (a > b ? -1 : 1)):   " + calculateAverage(results));
console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results));
</script>

<body>

</body>
</html>

Output:

Source: stackoverflow…

Do comment if you know much better example or have any doubts on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

This site uses Akismet to reduce spam. Learn how your comment data is processed.