-1

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.

tnsaturday
  • 527
  • 2
  • 10
  • 31

2 Answers2

2

There is in fact a function for this: String.prototype.localeCompare:

const gamesSortedByTitle = games.sort((a, b) => a.title.localeCompare(b.title));

Also, just so you know, sort actually modifies the array, so you may want to deep clone the array before sorting.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

games.sort((a,b) => a.title.localeCompare(b.title)); You can look the documentation of this function here: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/localeCompare

Bamak
  • 188
  • 6