Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Sort Array String by Number then Letter

I am looking to sort an array containing movie title strings such as:

['Battleship','101 Dalmatians','Alice, Sweet Alice','40 Days of Night', '303 Fear Faith Revenge'...]

My expected output from this would be:

101 Dalmatians
303 Fear Faith Revenge
40 Days of Night
Alice, Sweet, Alice
Battleship

I am trying the following which gets close:

getMoviesInAlpOrder() {
    const movieList = this.getMovies();
    return movieList.sort(function(a, b) {
        return a.title.toLowerCase() > b.title.toLowerCase();
    });
}

This almost works but does have some conflicts when sorting the numbers versus character titles. Any suggestions on how best to handle this type of request?

like image 465
Yuschick Avatar asked May 31 '26 21:05

Yuschick


2 Answers

Although the other answers are correct, I think the following solution will be a bit more flexible.

Using localeCompare should solve your issue (and possibly future issues if you get text with accented characters!). Especially with movie titles, I'd expect there to be some foreign characters to sort.

getMoviesInAlpOrder() {
    const movieList = this.getMovies();
    return movieList.sort(function(a, b) {
        var lowerCaseA = a.title.toLocaleLowerCase();
        var lowerCaseB = b.title.toLocaleLowerCase();
        return lowerCaseA.localeCompare(lowerCaseB);
    });
}
like image 112
Chill Avatar answered Jun 02 '26 11:06

Chill


You can use Array.prototype.sort():

var arr = ['Battleship','101 Dalmatians','Alice, Sweet Alice','40 Days of Night', '303 Fear Faith Revenge'];
console.log(arr.sort());
like image 21
Yosvel Quintero Arguelles Avatar answered Jun 02 '26 09:06

Yosvel Quintero Arguelles