javascript - Javascript使用优先级数组对对象数组进行排序
问题描述
我有这个对象数组:
var eventList = [
{
eventName: "abc",
status: "completed"
},
{
eventName: "def",
status: "live"
},
{
eventName: "ghi",
status: "live"
},
{
eventName: "jkl",
status: "upcoming"
},
]
我想使用特定键的优先级数组对这些对象数组进行排序,比如["live", "upcoming", "completed"]
状态,这意味着所有实时事件首先出现,然后是即将到来的,然后是完成的。互联网上的答案似乎只能使用键对数组对象进行升序或降序排序。我该如何处理?
解决方案
您可以使用Array.prototype.sort()
带有排序数组的方法来做到这一点。
const eventList = [
{
eventName: 'abc',
status: 'completed',
},
{
eventName: 'def',
status: 'live',
},
{
eventName: 'ghi',
status: 'live',
},
{
eventName: 'jkl',
status: 'upcoming',
},
];
const order = ['live', 'upcoming', 'completed'];
eventList.sort((x, y) => order.indexOf(x.status) - order.indexOf(y.status));
console.log(eventList);
如果您想在排序时更快地进行索引搜索,您可以使用Map Object
.
const eventList = [
{
eventName: 'abc',
status: 'completed',
},
{
eventName: 'def',
status: 'live',
},
{
eventName: 'ghi',
status: 'live',
},
{
eventName: 'jkl',
status: 'upcoming',
},
];
const order = ['live', 'upcoming', 'completed'];
const map = new Map();
order.forEach((x, i) => map.set(x, i));
eventList.sort((x, y) => map.get(x.status) - map.get(y.status));
console.log(eventList);
推荐阅读
- css - 使 ng-select 宽度调整为所选项目/可用选项?
- ios - AVQueuePlayer 不播放长时间的 wav 音频
- ntfs - 如何从我的 Mac 中完全删除 Paragon NTFS?
- java - 无法在 Spring Boot 2 中绑定 Zipkin 枚举
- scheme - 如何计算一个列表中的模式出现在Scheme的另一个列表中的次数
- javascript - 将javascript创建的复选框传递给控制器以保存到表格?
- php - 编辑 PHP MySQL 时未出现旧值
- ruby-on-rails - 我安装了 rails 6 beta,但无法启动示例应用程序
- excel - 日期的 Excel 公式,但不包括空单元格
- c# - 解析文本文件以获取数据的有效方法