【发布时间】: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