1. Sorting:
The default sort() sorts by character encoding:
Now let it follow Sorting by numerical size:
Just pass a comparison function to sort. If the comparison function The value of is less than 0, which means that a must appear before b, otherwise it will appear after b.
2. Out of order: Just let the comparison function return -1 or 1 randomly:
3. Search: Using sort() to search is quite new, haha, let’s see how it works.
Now I want to find all the elements containing the letter 'a' in the array. If there is no sort(), it seems that I can only use traversal. The efficiency of traversal... That is scary! ! The specific method is as follows:
This way, the array contains letters' All the elements of a' are placed in front of the array, and after some simple processing, the search results can be output.
The above are the three methods I summarized for using sort() to operate arrays in JavaScript. If you are interested, you will find that sort() has many wonderful uses...