Sorting Chinese Characters in Javascript

May 27

Exempel kinesiska tecken
To start learning to write a plug-in for jQuery component Datatables  I have made a webpage  http://sorting.lcube.se/. You can try to sort on different terms there. I plan to explain how Chinese characters are sorted and tell how I make the sorting and what troubles i get into.
The first problem I had was that i thought  三 (san1) came after 二 (Er4). I was convinced that this was a bug. But after thinking about it I realized that number 3  三 (san1) has the radical 一 which has fewer strokes than the character for two which has two strokes in its radical.

Today there are just a few lines of code in the javascript. The trick is to use javascripts localCompare (localCompare ref). There are however known problem with this function for different web browsers. Allan Jardine author of Datatables have pointed this out to me. I will try to explore this further here on my blog and see if this gives problem for sorting Chinese characters.

$.fn.dataTableExt.oSort['chinese-string-asc'] = function (s1, s2) {
    return s1.localeCompare(s2);
};
$.fn.dataTableExt.oSort['chinese-string-desc'] = function (s1, s2) {
    return s2.localeCompare(s1);
};
 
/* Main Mother */
function ColorDataTablesInit(tableDivId) {
 
 
    $(tableDivId).dataTable({
        "sPaginationType": "full_numbers",
        "aoColumnDefs": [{
            "sType": "chinese-string",
            "aTargets": [1,2,3,4]
        }]
    });
 
}

4 comments

  1. james /

    nice sorting, this is impressive on how you sort on radical and pinyin. Do you mind if you can share the JS code? i am wondering are you using bubble sort or which sorting algorithm you did? I am trying to sort a country list in Chinese and i am having difficulty at the moment.

    thanks

  2. An example is here: http://sorting.lcube.se/
    I am just using the jquery component: datatables.net and too it I wrote a simple plugin that just uses the localCompare function. The localCompare function does the whole work.
    See more about datatables sorting feature here: http://datatables.net/plug-ins/sorting. Ask Allan Jardine what he uses ( author of Datatables). I think he probably uses built in sorting functions in javascript like eg:arraysort http://www.javascriptkit.com/javatutors/arraysort.shtml . But if it is an assignment to sort with a specific algorithm like quicksort or bubble you could use the localCompare function I talk about in my blogpost to decide which country comes before the other.

  3. Diana Marinova казва:Spored men ne trqbva da obqtsqvane na dulgo i na shiroko kakvo to4no pravite v saita i kak go pravite,zashtoto mnogo xora nqma da go razberat i samo zaemate prostranstvo !

  4. Hello blogger, i must say you have very interesting posts here.
    Your page should go viral. You need initial traffic only.
    How to get it? Search for; Mertiso’s tips go viral

Leave a Reply

Your email address will not be published.