我需要按如下方式订购字符串:
LU9,MA9,mi9,DO9,LU10,MA10,mi10,LU11,MA11,MI11
为此,我有以下代码:
var hours = "lu9,lu10,lu11,ma9,ma10,ma11,mi9,mi10,mi11,do9";
myExit = hours.split(',').sort(function (a, b) {
var reg = /\d+/;
var num = 2 * (+(0 + a.match(reg)) - +(0 + b.match(reg)));
var str = a > b ? 1 : a < b ? -1 : 0;
return num + str;
});
alert(myExit);
该代码工作正常,但问题是字符串是按字母顺序排序的:
DO9,LU9,MA9,mi9,LU10,MA10,mi10,LU11,MA11,MI11
“do9”应该是最后一个,所以:
LU9,MA9,mi9,DO9 ...
我们的想法是根据西班牙语中的星期几对此变量进行排序:
lu = lunes
ma = martes
mi = miercoles
ju = jueves
vi = viernes
sa = sabado
do = domingo
如何使用我的代码?
答案 0 :(得分:3)
var hours = "lu9,lu10,lu11,ma9,ma10,ma11,mi9,mi10,mi11,do9";
var arrIndex = {'lu' : 1,'ma':2,'mi':3,'ju':4,'vi':5,'sa':6,'do':7};
myExit = hours.split(',').sort(function (a, b) {
var reg = /\d+/;
var num = a.match(reg) - b.match(reg);
var strreg = /[a-zA-Z]*/;
var str = arrIndex[a.match(strreg)[0]] - arrIndex [ b.match(strreg)[0]];
return num * 20 + str;
});
alert(myExit);
console.log(myExit);
,输出为:
["lu9", "ma9", "mi9", "do9", "lu10", "ma10", "mi10", "lu11", "ma11", "mi11"]