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?
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);
});
}
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With