JavaScript provides an in-built method sort() for sorting arrays in ascending order. To sort an array in descending order, we can combine sort() method with another in-built method reverse().
Here's an example of sorting an array of numbers in ascending order using sort():
index.tsx143 chars4 linesIn the above example, sort() method takes a callback function as an argument which compares two consecutive elements of the array and returns a negative, zero, or positive value based on their relationship to each other. If the result is negative, element a comes before element b. If the result is positive, element b comes before element a. If the result is zero, the order of the elements is unchanged.
To sort an array in descending order, we can simply add reverse() method after sort() method as shown below:
index.tsx153 chars4 linesIn the above example, sort() method sorts the array in ascending order and reverse() method reverses the order, which makes it a descending order sort.
gistlibby LogSnag