How to use sort() method and comparator function in Javascript

  • Initialize an array with some values.
  • Sort the array with the modified sort() method.
  • Pass a callback function as a parameter inside the sort method.
  • It will be a comparator function that will sort in descending order.

Example: This example implements the above approach.

Javascript




const arr1 = [24.6,23.7,18.9,76.5];
const arr2 = [54,23,12,97,100];
 
function arrSort(arr) {
    arr.sort((a,b)=>b-a);
    return arr;
}
 
console.log(arrSort(arr1));
console.log(arrSort(arr2));


Output

[ 76.5, 24.6, 23.7, 18.9 ]
[ 100, 97, 54, 23, 12 ]

Sort an array in reverse order JavaScript

Sorting is a basic algorithm that is used in many programming languages. Most languages provide in-built methods to sort an array. In JavaScript we use the sort() method to sort an array in ascending order. To sort an array in the reverse order that is descending order there are no built-in methods to perform this task but we can combine different methods together to sort the array in reverse order.

These are the following methods for solving this problem:

Table of Content

  • Using sort() method and reverse() method
  • Using sort() method and comparator function
  • Using sort() method and Lodash _.reverse() function

Similar Reads

Approach 1: Using sort() method and reverse() method

Initialize an array with some values. Sort the array using the sort() method  Reverse the array using the reverse() method....

Approach 2: Using sort() method and comparator function

...

Approach 3: Using sort() method and Lodash _.reverse() function

Initialize an array with some values. Sort the array with the modified sort() method. Pass a callback function as a parameter inside the sort method. It will be a comparator function that will sort in descending order....

Conclusion:

...

Contact Us