The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order.
Sample Code
Output
Numeric Sort
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function.
Sample Code
Output
Use the same trick to sort an array descending:
The Compare Function
The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments.
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
If the result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, no changes are done with the sort order of the two values.
Sample Code
Output
Sorting an Array in Random Order
Find the Highest (or Lowest) Array Value
There are no built-in functions for finding the max or min value in an array.
However, after you have sorted an array, you can use the index to obtain the highest and lowest values.
Sorting ascending.
Using Math.max() on an Array
You can use Math.max.apply to find the highest number in an array.
Using Math.min() on an Array
You can use Math.min.apply to find the lowest number in an array.
Related Searches to JavaScript Array Sort - JavaScript Sorting Arrays
javascript sorting arrays javascript array sort() method javascript array sort sorting an array more effectively javascript sort array what is the best way to sort an array in javascript can you sort an array in javascript how to sort an array of array in javascript what is the fastest way to sort an array javascript how to sort numeric array using javascript sort array of objects javascript javascript sort array sort java sort array in ascending order javascript javascript sort array of numbers javascript sort by date