views:

163

answers:

2

I'm looking for the easiest way to sort an array that consists of numbers and text, and a combination of these.

E.g.

'123asd'
'19asd'
'12345asd'
'asd123'
'asd12'

turns into

'19asd'
'123asd'
'12345asd'
'asd12'
'asd123'

This is going to be used in combination with the solution to another question I've asked here.

The sorting function in itself works, what I need is a function that can say that that '19asd' is smaller than '123asd'.

I'm writing this in JavaScript.

Edit: as adormitu pointed out, what I'm looking for is a function for natural sorting

+1  A: 

So you need a natural sort? If so, than maybe this script would be what you need.

mhitza
Correct, natural sort is what I'm looking for. I'll look in to the link you sent, thanks
ptrn
This certainly did the trick. Thanks so much!
ptrn
A: 
function a1Sort(a, b){
    var cnt= 0, tem;
    a= String(a).toLowerCase();
    b= String(b).toLowerCase();
    if(a== b) return 0;
    if(/\d/.test(a) ||  /\d/.test(b)){
        var Rx=  /^\d+(\.\d+)?/;
        while(a.charAt(cnt)=== b.charAt(cnt) && 
        !Rx.test(a.substring(cnt))){
            cnt++;
        }
        a= a.substring(cnt);
        b= b.substring(cnt);
        if(Rx.test(a) || Rx.test(b)){
            if(!Rx.test(a)) return a? 1: -1;
            if(!Rx.test(b)) return b? -1: 1;
            tem= parseFloat(a)-parseFloat(b);
            if(tem!= 0) return tem;
            a= a.replace(Rx,'');
            b= b.replace(Rx,'');
            if(/\d/.test(a) ||  /\d/.test(b)){
                return a1Sort(a, b);
            }
        }
    }
    if(a== b) return 0;
    return a> b? 1: -1;
}

var arr=['123asd','19asd','12345asd','asd123','asd12']; arr.sort(a1Sort)

/* returned value: (Array) 19asd,123asd,12345asd,asd12,asd123 */

kennebec
would this work in my case, with the inner array deciding the order of the outer one?
ptrn
What's `String.prototype.tlc()`? Is this your own code or did you get it from somewhere? If the latter, please link to the page.
Andy E
sorry about the mistake- corrected, thank you.If you want a[1] and b[1] to control the sort, use a= String(a[1]).toLowerCase(); b= String(b[1]).toLowerCase();
kennebec