简体   繁体   中英

sort array on 2 level in javascript

I have this array:
var temp_arr = ["4~3", "4~6", "4~1", "4~8", "2~7", "2~0", "2~4", "7~5", "7~9", "7~7", "0~2", "0~0", "4~4", "4~5", "4~7"];

And I want to sort using value , which is before tild and then with value which is after the tild .

I found few solutions on internet but its not working.

var temp_arr = ["4~3", "4~6", "4~1", "4~8", "2~7", "2~0", "2~4", "7~5", "7~9", "7~7", "0~2", "0~0", "4~4", "4~5", "4~7"];

temp_arr.sort(function(a,b){
    return Number(a.split('~')[0]) - Number(b.split('~')[0]);
});

    temp_arr.sort(function(a,b){
        var a_ = Number(a.split('~')[1]);
        var b_ = Number(b.split('~')[1]);
        var a2 = Number(a.split('~')[0]);
        var b2 = Number(b.split('~')[0]);
        if(a2 != b2)
        {
            return 0;
        }
        else if(a_ != b_)
        {
            return a_ > b_;
        }
    });
    console.log(temp_arr);


Here is jsFiddle

You can use this code:

var temp_arr = ["4~3", "4~6", "4~1", "4~8", "2~7", "2~0", "2~4", "7~5", "7~9", "7~7", "0~2", "0~0", "4~4", "4~5", "4~7"];

for(var i = 0; i < temp_arr.length; i++)
{
    for(var it = 0; it < temp_arr.length-1; it++)
    {
        var it1 = temp_arr[it];
        var it2 = temp_arr[it+1];
        var right1 = Number(it1.split('~')[1]);
        var right2 = Number(it2.split('~')[1]);
        var left1 = Number(it1.split('~')[0]);
        var left2 = Number(it2.split('~')[0]);
        if(left1 > left2 || (right1 > right2 && left1 == left2))
        {
            var temp = temp_arr[it];
            temp_arr[it] = temp_arr[it+1];
            temp_arr[it+1] = temp;
        }
    }
}
console.log(temp_arr);

It's using a modified version of bubble sort.

Fiddle

Edit: Made it a bit shorter

If you want a shorter piece of code using your idea, you can use

var temp_arr = ["4~3", "4~6", "4~1", "4~8", "2~7", "2~0", "2~4", "7~5", "7~9", "7~7", "0~2", "0~0", "4~4", "4~5", "4~7"];

temp_arr.sort(function(a,b){
   var t = Number(a.split('~')[0]) - Number(b.split('~')[0]);
   if (t == 0)
       return Number(a.split('~')[1]) - Number(b.split('~')[1]);
   else 
       return t;
});

console.log(temp_arr);

Hope it helps Dan

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