freemann098
freemann098

Reputation: 284

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 sorts it by the first character in the number or word. So if 22, 1, and 3 was entered, it would sort it by 1,22,3 because of being sorted by first character. The same goes with words. How would I get past this? If you think my code would help you tell me how, here you go.

var input = null;
var words = new Array();

function startApp()
{
    alert("Welcome to Word/Number Sorter 1.0");
    alert("Enter one word/number at a time in the next prompts. Enter passw0rd to finish/stop.");

    do {

        input = prompt("Enter word...enter passw0rd to exit.");
        if ( input != "passw0rd" ){
            words.push(input);
        }
        else{
            break;
        }
    }while( input != "passw0rd" );

    var newW = words.sort();

    for ( var i = 0; i < newW.length; i++ )
    {
        document.writeln(newW[i], "<br>");
    }
}

Upvotes: 0

Views: 3476

Answers (1)

georg
georg

Reputation: 214969

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:

function natcmp(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"]

Upvotes: 1

Related Questions