-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.

4
  • 2
    return a.title.localeCompare(b.title) Commented Aug 6, 2020 at 12:23
  • stackoverflow.com/q/51165/1497533 Commented Aug 6, 2020 at 12:23
  • Unless you explicitly need to downcase, in which case the same thing, just downcase. Commented Aug 6, 2020 at 12:24
  • @CBroe OTOH, "0xAA" - "0xAB" or "10" - "5". It may not make sense, but JavaScript. Commented Aug 6, 2020 at 12:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.