Examples of sort () usage in javascript and javascript
This article analyzes the usage of sort () in javascript. Share it with you for your reference. The specific analysis is as follows:
Function Syntax:
ArrayObject. sort (sortby)
You think this is not the right way but you love it
The split function is also used here to go to an array of strings, which is commonly used. Then, sort the values in the logarithm group by the sort function sort () of the array to obtain a new array. Then, the sorted string is obtained by outputting the array content cyclically.
In this example, It is sorted by ascii code by default.
What if it's a number? Try it ~
Modify the value of p as follows:
20 38 19 32 654 2 123 454 4
Running result: 123 19 2 20 32 38 4 454 654
It is sorted by character encoding, rather than the value size.
To sort numbers, you need to write a few more lines of code:
The modified code is as follows:
Originarr = originarr. sort (function (a, B) {return a-B ;});
Running result: 2 4 19 20 32 38 123 454
The above sorting is in the positive order. If it is in reverse order, you need to change it again:
Change return a-B in the function to return B-.
The changed code is as follows:
Originarr = originarr. sort (function (a, B) {if (a> B) return-1; if (a <B) return 1; return 0 ;});
I hope this article will help you design javascript programs.