javascript - 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;
}
问题是有没有办法以更简单的方式做到这一点?就像我上面显示的分数一样。
解决方案
实际上有一个功能String.prototype.localeCompare
:
const gamesSortedByTitle = games.sort((a, b) => a.title.localeCompare(b.title));
此外,正如您所知,sort
实际上修改了数组,因此您可能希望在排序之前对数组进行深度克隆。
推荐阅读
- r - 如何自动找到多个变量的偏相关
- debugging - 如何使用 gdb 调试 gtk 应用程序?
- android - 如何在 Android 项目中找到未使用的依赖项?
- c - nRF52 与 PCA9685
- postgresql - 锁定分区父表
- windows - 您可以通过批处理将命令传递到正在运行的程序中吗?
- php - 当我放置文件夹地址而不是 URL 时,unserialize() php 函数没有转换
- reactjs - 将 CSS 转换为样式化组件问题
- python - 使用 Python 在 Raspberry Pi 上打开程序?
- hadoop - 通过 hadoop FileSystem api 访问 Azure Storage Emulator