JS hybrid sorting (similar to the address book sorting in Chinese mobile operating system)

Time:2019-12-8

In the afternoon when the sun is shining and the most suitable for dozing, the specially mute mobile phone actually moves. You can see it right. It vibrates

God (customer) calls, “the Chinese name of the device in the tree menu on the left side of the report query system cannot be sorted”. To add sorting function…. Bu la… Bu la…, add XXX, add XXX

Let’s start!Forgive me for all the crap

Gorgeous dividing line


 

Direct code

The data to be sorted is as follows:

 

Here is the code(Crap):

//Alphanumeric Chinese mixed sorting
 function arrSortMinToMax(a, b) {
     //Judge whether it starts with numbers; why judge? Look at the source data
     if (/^\d+/.test(a.Name) && /^\d+/.test(b.Name)) {
         //Extract the starting number and compare the return
         return /^\d+/.exec(a.Name) - /^\d+/.exec(b.Name);
         //If Chinese is included, it shall be sorted by Chinese Pinyin
     } else if (isChinese(a.Name) && isChinese(b.Name)) {
         //Compare strings according to Pinyin
         return a.Name.localeCompare(b.Name, 'zh-CN')
     } else {
         //Sort numbers and letters
         return a.Name.localeCompare(b.Name, 'en');
     }
 }
 
 //Check whether it is Chinese, true means Chinese, false means non Chinese
 function isChinese(str) {
     //Chinese universal code regular
     if (/[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d]/.test(str)) {
         return true;
     } else {
         return false;
     }
 }

The sorting results are as follows:

 

Finish work!

That’s right. It took less than 20 lines of code to implement this sort. At first, I took it seriously. I thought it could be done in minutes (I’m not good at front-end apes), and it took me a long time

 

 

In fact, the key to sorting is Chinese Pinyin, and the string of “beginning of number” should be sorted according to the previous number first. Well, in order to realize the following information, students who are interested in re optimizing can refer to the following links:

http://www.unicode.org/charts/

http://www.unicode.org/reports/tr38/#BlockListing

 

String. Prototype. Localecompare() details

https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/string/localecompare#Examples