首页 > 解决方案 > JavaScript sort() 方法的更简单方法

问题描述

我有一系列对象,为一些电子游戏建模:

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

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

标签: javascriptsorting

解决方案


实际上有一个功能String.prototype.localeCompare

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

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


推荐阅读