JavaScript - Sort an Array in Reverse Order in JS
JS array.sort() Method sorts the array in ascending order. We can make it descending or reverse order using array.reverse() method. Below are the following ways to sort an array in reverse order:
1. Using array.sort() with array.reverse()
First, sort the given array of strings using JS array.sort() method.
const a = [ "JS", "CSS", "HTML" ]
a.sort();
console.log(a)
const a = [ "JS", "CSS", "HTML" ]
a.sort();
console.log(a)
Output
[ 'CSS', 'HTML', 'JS' ]
Now, use the array.reverse() method to reverse the array and get sort the array in descending order.
const a = [ "JS", "CSS", "HTML" ]
// Sort in ascending order
a.sort();
// Reverse the order
a.reverse()
console.log(a)
const a = [ "JS", "CSS", "HTML" ]
// Sort in ascending order
a.sort();
// Reverse the order
a.reverse()
console.log(a)
Output
[ 'JS', 'HTML', 'CSS' ]
We have have an article Reverse an Array in JavaScript by using some other approaches as well please go through this article to clear your concept.
2. Using the Comparator Function
For Numeric Array
Use the comparision function to subtract first item from second to get the reverse order.
const arr = [ 10, 20, 25, 100 , 40]
// Pass the comparator to to sort in reverse order
arr.sort((a,b) => b - a)
console.log(arr)
const arr = [ 10, 20, 25, 100 , 40]
// Pass the comparator to to sort in reverse order
arr.sort((a,b) => b - a)
console.log(arr)
Output
[ 100, 40, 25, 20, 10 ]
Please go through this How to Sort Numeric Array using JavaScript?, to know how the JavaScript array sort function works.
For Array of Strings
Use string.localeCompare() to compare first element relative to second element.
// Original array
let arr = ["JS", "HTML", "CSS" ];
console.log(arr);
// Sort in reverse order
arr.sort( (a,b) => b.localeCompare(a))
console.log(arr);
// Original array
let arr = ["JS", "HTML", "CSS" ];
console.log(arr);
// Sort in reverse order
arr.sort( (a,b) => b.localeCompare(a))
console.log(arr);
Go through this article, sort array of strings in JS, to learn more about sorting strings Array in JavaScript.
3. Using Lodash.sortBy() Method
Lodash _.sortBy() method sorts the array in ascending order. We can get the reverse array by passing additional parameter.
const _ = require('lodash');
const arr = [10, 20, 25, 100, 40];
// Sort in descending with a custom iteratee
_.sortBy(arr, (n) => -n);
console.log(arr);
Output
[100, 40, 25, 20, 10]
4. Using Lodash _.reverse()Method
Lodash _.reverse() Method reverses and updates the original array. Use it on the sorted array to get the descending order.
const _ = require('lodash');
const arr = [10, 20, 25, 100, 40];
// Sort the array
arr.sort((a, b) => a - b);
// Then reverse the orignal sorted array
_.reverse(arr);
console.log(arr);
Output
[100, 40, 25, 20, 10]