1. 程式人生 > >將陣列按照拼音排序,並按字母排序

將陣列按照拼音排序,並按字母排序

按拼音排序:

var resultArray = arr.sort(          //陣列按照abcd排列
            function compareFunction(param1, param2) {
                return param1.localeCompare(param2,"zh");
            }
    );

將陣列按照拼音排序(多音字無法辨別,需手動區分),並按字母分類:

function pySegSort(arr,empty) {
        if(!String.prototype.localeCompare)
            return null;

        var letters = "*ABCDEFGHJKLMNOPQRSTWXYZ".split('');
        var zh = "阿吧擦大額發噶哈雞看啦嘛拿哦怕去讓仨他哇西呀咋".split('');
        console.log(letters.length+"-----------------"+zh.length)
        var segs = [];
        var curr;
        $.each(letters, function(i){
            curr = {letter: this, data:[]};
            $.each(arr, function() {
//                if((!zh[i-1] || zh[i-1].localeCompare(this,"zh") <= 0) && this.localeCompare(zh[i],"zh") == -1) {
//                    curr.data.push(this);
//                }
                if((!zh[i-1] || zh[i-1].localeCompare(this,"zh") <= 0) && this.localeCompare(zh[i],"zh") == -1) {
                    curr.data.push(this);
                }
            });
            if(empty || curr.data.length) {
                segs.push(curr);
                curr.data.sort(function(a,b){
                    return a.localeCompare(b,"zh");
                });
            }
        });
       // console.log("1--------------"+typeof segs );
        return segs;
    }