This article analyzes the usage of sort() in javascript with examples. Share it with everyone for your reference. The specific analysis is as follows:
Syntax of function:
arrayObject.sort(sortby)
you think this is not the right way but you love it
The split function is also used here, the purpose is to get an array of strings, which is more commonly used. Then the values in the array are sorted through the array's sorting function sort() to obtain a new array, and then the sorted string is obtained by looping through the contents of the array.
In the example, by default, it will be sorted according to ascii code.
What if it were numbers? Give it a try~
Modify the value in p as follows:
20 38 19 32 654 2 123 454 4
The running result is: 123 19 2 20 32 38 4 454 654
It is sorted according to the 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; });
Run results: 2 4 19 20 32 38 123 454 654
The above sorting is in positive order. If it is in reverse order, then you need to change it again:
Just change return a - b; in the function to return b - a.
If it is alphabetical 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 design.