Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptSort an array in reverse order JavaScript

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 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.

Approach 1:

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

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)=>a-b);
    arr.reverse();
    return arr;
}
  
console.log(arrSort(arr1));
console.log(arrSort(arr2));


Output: The comparator function in this approach sorts in ascending order.

(4) [76.5, 24.6, 23.7, 18.9]
(5) [100, 97, 54, 23, 12]

Approach 2:

  • Initialize an array with some values.
  • Sort the array with 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: We use a modified comparator function in this approach which returns a negative value so sorting is automatically done in reverse order.

(4) [76.5, 24.6, 23.7, 18.9]
(5) [100, 97, 54, 23, 12]

Conclusion:

There is no predefined method to sort an array in reverse order but we can create additional methods to sort in descending order. We can combine some array methods to reverse in descending order or we can create a custom comparator function to sort in descending order.

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments