简体   繁体   中英

Sort string using a specific format

I need to order a string as follows:

lu9,ma9,mi9,do9,lu10,ma10,mi10,lu11,ma11,mi11

To do this, I have the following code:

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);

That code works fine, but the problem is that the string is ordered alphabetically:

do9,lu9,ma9,mi9,lu10,ma10,mi10,lu11,ma11,mi11

The "do9" should be the last, so:

lu9,ma9,mi9,do9...

The idea is to sort this variable according to the day of the week in Spanish:

lu = lunes

ma = martes

mi = miercoles

ju = jueves

vi = viernes

sa = sabado

do = domingo

How I can do using my code?

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);

and the output is :

["lu9", "ma9", "mi9", "do9", "lu10", "ma10", "mi10", "lu11", "ma11", "mi11"] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM