Multiple Sort () Functions and sort Functions
The sort () method is used to sort the elements of an array. Included in header file algorithm
Syntax
ArrayObject. sort (sortby)
Parameters |
Description |
Sortby |
Optional. Specify the sorting order. Must be a function. |
Return Value
Array reference. Note that arrays are sorted on the original array without generating copies.
I. Default situation
By default, the sort () method arranges array items in ascending order. To achieve sorting, the sort () method calls the toString () transformation method of each array item, and then compares the obtained string to determine how to sort it. As follows:
Var values = ["orange", "apple", "banana"]; values. sort (); console. log (values); // result ["apple", "banana", "orange"]
However, even if each item in the array is a numerical value, the sort () method compares strings as follows:
Var values = [,]; values. sort (); console. log (values); // result [,]
Ii. Sort the values
The sort () method can receive a comparison function as a parameter.
The comparison function receives two parameters. If the first parameter is before the second parameter, a negative number is returned. If the two parameters are equal, 0 is returned, if the first parameter is placed after the second parameter, a positive number is returned.
Function compare (a, B) {return (a-B) ;}// comparison function var values = [,,]; values in ascending order. sort (compare); console. log (values); // result [,]
3. Sort the Array Based on an object property
Define a function, which receives an attribute name, and then creates a comparison function based on the attribute name. The following is the definition of this function:
Function createComparisonFunction (propertyName) {return function (object, object) {var a = object [propertyName]; var B = object [propertyName]; if (a <B) {return-;} else if (a> B) {return;} else {return ;}}// return a comparison function created based on the attribute name in ascending order.
After the internal function receives the propertyName parameter, it uses square brackets to obtain the value of the given attribute.
The above function can be used as in the following example.
var data = [{name:"Lily", age: }, {name:"Judy", age: }];data.sort(createComparisonFunction("name"));console.log(data[].name);//Judydata.sort(createComparisonFunction("age"));console.log(data[].name);//Lily
The above content is a series of Sort () function usage, I hope to help you above!
Articles you may be interested in:
- Example Analysis of sort function usage in Arraylist in C #
- Php array sorting usort, uksort, and sort functions usage
- Example of qsort function usage in C Language
- Analysis of sort function usage in C/C ++
- Summary and examples of Perl Sort function usage