This article is the official HTML5 training tutorial of H5EDU organization. It mainly introduces: JavaScript intensive tutorial - sort() method
Example
Array sorting: var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); fruits output results: Apple, Banana, Mango, Orange
Definition and usage
sort() method is used to sort the elements of the array.
The sort order can be alphabetical or numerical, and in ascending or descending order.
The default sort order is ascending alphabetically.
Note: When the numbers are arranged in alphabetical order, "40" will be listed before "5".
To use numerical sorting, you must call it with a function as a parameter.
The function specifies whether the numbers are arranged in ascending or descending order.
These may be difficult to understand, you can learn more about it through the examples at the bottom of this page.
Note: This method will change the original array! .
array.sort(sortfunction) Parameter Values
Parameter Description
sortfunction Optional. Specifies the sort order. Must be a function.
Return Value
Type Description
Array A reference to the array. Please note that the array is sorted on the original array, no copy is made.
Example
Number sorting (numeric and ascending order):
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
fruits output results:
1,5,10,25,40,100
Example
Numerical sorting (numeric and descending order):
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});
fruits output results:
100,40,25,10,5,1
Example
Numerical sorting (alphabetical and descending order):
var fruits = ["Banana", "Orange", "Apple", " Mango"];
fruits.sort();
fruits.reverse();
fruits output results:
Orange,Mango,Banana,Apple