I have an array of objects, modeling some videogames:
let games = [
{title: 'Desperados 3', score: 74, genre: ['Tactics', 'Real Time']},
{title: 'Streets of Rage', score: 71, genre: ['Fighting', 'Side Scroller']},
{title: 'Gears Tactics', score: 71, genre: ['Tactics', 'Real Time']},
{title: 'XCOM: Chimera Squad', score: 59, genre: ['Tactics', 'Turn Based']},
{title: 'Iratus Lord of The Dead', score: 67, genre: ['Tactics', 'Side Scroller']},
{title: 'DooM Eternal', score: 63, genre: ['Shooter', 'First Person']},
{title: 'Ghost Of Tsushima', score: 83, genre: ['Action', '3rd Person']},
{title: 'The Last Of Us Part 2', score: 52, genre: ['Shooter', '3rd Person']}
]
If I want to sort it by games' scores it's very easy:
const gamesSortedByRating = games.sort((a, b) => b.score - a.score);
But I've found out, that in order to sort it by games titles, it cannot be (or, at least I wasn't able to) do it this way:
const gamesSortedByTitle = games.sort((a, b) => a.title - b.title);
I had to write a compare function to do that:
function compare(a, b) {
const titleA = a.title.toLowerCase();
const titleB = b.title.toLowerCase();
let comparison = 0;
if (titleA > titleB) {
comparison = 1;
} else if (titleA < titleB) {
comparison = -1;
}
return comparison;
}
The question is is there any way to do that in a more simple way? Like the score one liner I've shown above.