javascript - 按特定对象键排序
问题描述
我有一个这样的对象数组:
const cars = [
{
id: 'a1c1',
position: 3,
name: 'Car 3',
},
{
id: 'b9f6',
position: 1,
name: 'Car 1',
},
{
id: '3b6d',
position: 2,
name: 'Car 2',
},
];
现在我按位置排序,从头到尾,像这样:
const sorted = cars.sort((a, b) => a.position - b.position);
然后我有一个带有等级的对象,这些等级值与汽车对象中的 id 相同:
const carsByRank = {
good: 'b9f6',
best: '3b6d',
average: 'a1c1',
};
我需要从这些数据中得到什么:当我对数据进行排序时,我需要最好的汽车排在第一名,第二名,平均第三名,以及任何其他没有排名的汽车,都在这些之下。我怎样才能做到这一点?
解决方案
如果“最好”在前,那是您在内部的第一次检查sort
以返回-1
(a 在 b 之前)或1
(a 在 b 之后)。然后检查“好”,然后检查“平均”。
作为你的前三个,这是最好的、好的和平均的。然后,如果需要,您可以继续按位置订购。
注意: Array.prototype.sort
确实返回排序后的数组,但也会修改原始数组
我添加了一些额外的对象以更好地显示排序和后续基于位置的排序。
const cars = [{
id: 'a1c1',
position: 3,
name: 'Car 3',
},
{
id: 'a2a2',
position: 5,
name: 'Junker 1'
},
{
id: 'a2a3',
position: 6,
name: 'Junker 2'
},
{
id: 'b9f6',
position: 1,
name: 'Car 1',
},
{
id: 'a2a4',
position: 7,
name: 'Junker 3'
},
{
id: '3b6d',
position: 2,
name: 'Car 2',
},
{
id: 'a2a5',
position: 4,
name: 'Junker 4'
},
];
const carsByRank = {
good: 'b9f6',
best: '3b6d',
average: 'a1c1',
};
/* sort is in-place and modifies the array */
cars.sort((a, b) => {
if (a.id === carsByRank.best) return -1;
else if (b.id === carsByRank.best) return 1;
else if (a.id === carsByRank.good) return -1;
else if (b.id === carsByRank.good) return 1;
else if (a.id === carsByRank.average) return -1;
else if (b.id === carsByRank.average) return 1;
else return a.position - b.position;
});
console.log(cars);
推荐阅读
- flutter - 如何在 Dart/Flutter 中获取整个月的天数?
- java - 使用 if 语句为变量赋值
- ios - Twitter登录异常颤动
- c# - UWP RichEditBox RightClick->Paste 未触发 Paste 事件
- python - 为什么用于跨行比较值的向量化 python 代码不起作用?
- discord.js - Discord.js bot 向它所在的每个服务器中的特定频道发送消息
- version-control - hg diff 显示特定目录中文件的不相关更改
- ruby-on-rails - Grunt 还是 Sprockets 更适合应对铁轨
- c# - 有没有办法在 Windows 中使用 C# 以编程方式禁用磁盘驱动器上的写入缓存策略?
- javascript - Web 应用程序不断在外部浏览器中打开新页面