【问题标题】:Simpler approach to JavaScript sort() method [duplicate]JavaScript sort() 方法的更简单方法[重复]
【发布时间】:2020-08-06 12:20:37
【问题描述】:

我有一个对象数组,为一些电子游戏建模:

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']}
]

如果我想按游戏分数对其进行排序,这很容易:

const gamesSortedByRating = games.sort((a, b) => b.score - a.score);

但我发现,为了按游戏名称对其进行排序,不能(或者,至少我不能)这样做:

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

我必须编写一个比较函数来做到这一点:

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;
}

问题是有没有更简单的方法来做到这一点?就像我上面显示的分数线一样。

【问题讨论】:

  • return a.title.localeCompare(b.title)
  • 除非您明确需要小写,在这种情况下,同样的事情,只需小写。
  • @CBroe OTOH、"0xAA" - "0xAB""10" - "5"。它可能没有意义,但 JavaScript。

标签: javascript sorting


【解决方案1】:

实际上有一个函数:String.prototype.localeCompare:

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

另外,正如您所知,sort 实际上修改了数组,因此您可能希望在排序之前对数组进行深度克隆。

【讨论】:

    【解决方案2】:

    games.sort((a,b) =&gt; a.title.localeCompare(b.title)); 你可以在这里查看这个函数的文档:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/localeCompare

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 2019-03-24
      • 1970-01-01
      • 2021-01-05
      • 2012-12-13
      相关资源
      最近更新 更多