Skip to content Skip to sidebar Skip to footer

Javascript - Array Sorting Only First Letter/only First Number

I wrote a program in JavaScript that gathers input from user and sorts it alphabetically or if numbers alphanumerically. It's uses an array and sorts that array but JavaScript only

Solution 1:

To sort numerically you need a special sorting callback:

[22,1,3].sort(function(a, b) { return a - b })
> [1, 3, 22]

If you want "natural sorting", it goes like this:

functionnatcmp(a, b) {
    var ra = a.match(/\D+|\d+/g);
    var rb = b.match(/\D+|\d+/g);
    var r = 0;

    while(!r && ra.length && rb.length) {
        var x = ra.shift(), y = rb.shift(),
            nx = parseInt(x), ny = parseInt(y);

        if(isNaN(nx) || isNaN(ny))
            r = x > y ? 1 : (x < y ? -1 : 0);
        else
            r = nx - ny;
    }
    return r || ra.length - rb.length;
}

ls = ['img35', 'img1', 'img2', 'img22', 'img3', 'img2.gif', 'foobar']
console.log(ls.sort(natcmp))

> ["foobar","img1","img2","img2.gif","img3","img22","img35"]

Post a Comment for "Javascript - Array Sorting Only First Letter/only First Number"