0

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>");
    }
}
1

1 Answer 1

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:

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but then how would I fix the word sorting?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.