This article analyzes the usage of sort() in javascript. Share it 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, with the purpose of going to an array of strings, which is more commonly used. Then sort the values in the array through the sort function sort() of the array to obtain a new array, and then output the contents of the array by looping to obtain the sorted string.
In the example, by default, it will be sorted by ascii code.
If it is a number, what will happen? Try it ~
Modify the value in p as follows:
20 38 19 32 654 2 123 454 4
The operation result is: 123 19 2 20 32 38 4 454 654
It is sorted by character encoding, not the size of the value.
If you want 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 results: 2 4 19 20 32 38 123 454 654
The above sorts are all sorted in the positive order. If it is in the reverse order, then it needs to be changed:
Change the return a - b; in the function to return b - a.
If it is a letter sorting, 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 be helpful to everyone's JavaScript programming.