How to use sort() method and Lodash _.reverse() function in Javascript

  • In this appraoch, we are using Lodash _.reverse() method for reversing the given array.
  • We first sort our array then we will reverse it by using _.reverse() method and print the result in the console.

Example: This example implements the above approach.

Javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = [1, 7, 3, 4]
 
// Printing original Array
console.log("original Array1: ", array1)
 
array1.sort();
// Using _.reverse() method
let reversedArray = _.reverse(array1);
 
// Printing the reversedArray
console.log("reversed Array: ", reversedArray)


Output:

original Array1:  [ 1, 7, 3, 4 ]
reversed Array: [ 7, 4, 3, 1 ]

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