This article is mainly for you to share an example of the sort () function of the principle and use of the method, has a good reference value, I hope to be helpful to everyone. Follow the small series together to see it, hope to help everyone.
The sort () method is to sort the array according to a certain condition.
The sort () method, without parameters, defaults to sorting array elements as String types in ascending order, according to their Unicode codes from small to large.
If you want to sort by your own criteria, you need to pass a comparison function.
As follows:
var arr = [' A ', ' C ', ' B '];console.log (Arr.sort ());
The value of the output is
I see an example in the red Book of JavaScript that is very good:
Let's start by creating a comparison function:
function Createcomparisonfunction (PropertyName) { return function (object1,object2) { var value1 = object1[ PropertyName]; var value2 = Object2[propertyname]; return value2-value1;};
Note that this value2-value1 is in descending order, and if it is value1-value2 it is sorted in ascending order
Define an array:
var data = [ {name: "Ahang", age:28}, {name: "Cao", age:29}, {name: "Bang", age:30}, {name: "Diu", age:40 }];console.log (Data.sort (Createcomparisonfunction ("Age"));
Related recommendations:
Several usages of the sort function
Sort function
C + + sort () function