Home  >  Article  >  Backend Development  >  Detailed examples of the principles and usage of the sort() function

Detailed examples of the principles and usage of the sort() function

零到壹度
零到壹度Original
2018-03-30 15:25:034330browse

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

sort function

c++ 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn