The javascriptsort () method is used to sort array elements. This article introduces how to use javascriptSort () through examples. For more information, see this article. The sort () method is used to sort the elements of an array. Included in header file algorithm
Javascript Sort syntax
arrayObject.sort(sortby)
Parameters |
Description |
Sortby |
Optional. Specify the sorting order. Must be a function. |
Javascript Sort Return Value
Array reference. Note that arrays are sorted on the original array without generating copies.
I. Default situation of javascript Sort
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 values using javascript Sort
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 [,]
Iii. javascript Sort sorts arrays based on certain object attributes
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