JS對省市按首字母排序
阿新 • • 發佈:2019-02-07
/**
* 省市拼音排序
*/
function pySegSort(arr, empty) {
if(!String.prototype.localeCompare)
return null;
var letters = "*ABCDEFGHJKLMNOPQRSTWXYZ".split('');
var zh = "阿八嚓噠妸發旮哈譏咔垃痳拏噢妑七呥扨它穵夕丫帀".split('');
var segs = [];// 存放資料
var py = [];// 存放首字母
var res = {};
var curr;
$.each(letters, function (i) {
curr = {
letter: this,
data: []
};
$.each(arr, function(k, v) {
if((!zh[i - 1] || zh[i - 1].localeCompare(v.cityName) <= 0) && v.cityName.localeCompare(zh[i]) == -1) {
curr.data.push(this);
}
});
if (empty || curr.data.length) {
py.push(this);
segs.push(curr);
curr.data.sort(function(a, b) {
return a.cityName.localeCompare(b.cityName);
});
}
});
res["segs"] = segs;
res["py"] = py;
return res;
}
/**
* 呼叫排序
*/
function pinyin() {
var arr2 = [
{"id" : "v1", "cityName" : "北京"},
{"id" : "v2", "cityName" : "上海"},
{"id" : "v5", "cityName" : "天津"},
{"id" : "v7", "cityName" : "安徽"},
{"id" : "v3", "cityName" : "呼和浩特"},
{"id" : "v4", "cityName" : "包頭"},
{"id" : "v9", "cityName" : "海南"},
{"id" : "v8", "cityName" : "張家口"}
];
var str = pySegSort(arr2);
JSON.stringify(str);
}
排序後內容如下:
{“segs”:[{“letter”:”A”,”data”:[{“id”:”v7”,”cityName”:”安徽”}]},{“letter”:”B”,”data”:[{“id”:”v4”,”cityName”:”包頭”},{“id”:”v1”,”cityName”:”北京”}]},{“letter”:”H”,”data”:[{“id”:”v9”,”cityName”:”海南”},{“id”:”v3”,”cityName”:”呼和浩特”}]},{“letter”:”S”,”data”:[{“id”:”v2”,”cityName”:”上海”}]},{“letter”:”T”,”data”:[{“id”:”v5”,”cityName”:”天津”}]}],”py”:[“A”,”B”,”H”,”S”,”T”]}