This article mainly shares an example to explain the principle and usage of the sort() function in detail. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.
The sort() method is to sort the array according to certain conditions.
Without parameters, the sort() method defaults to sorting the array elements as string types in ascending order, sorting them in ascending order according to their unicode codes.
If you want to sort according to your own conditions, you need to pass a comparison function.
is as follows:
var arr = ['a','c','b']; console.log(arr.sort());
The output value is
I saw an example in the red book of javascript and thought it was very good :
We first create a comparison function:
function createComparisonFunction(propertyName) { return function (object1,object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; return value2 - value1;} };
Explain that value2-value1 is sorted 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
The above is the detailed content of Detailed examples of the principles and usage of the sort() function. For more information, please follow other related articles on the PHP Chinese website!