Javascript使用优先级数组对对象数组进行排序

时间:2021-01-08 12:10:14

标签: javascript node.js arrays sorting object

我有这个对象数组:

var eventList = [
    {
        eventName: "abc",
        status: "completed"
    },
    {
        eventName: "def",
        status: "live"
    },
    {
        eventName: "ghi",
        status: "live"
    },
    {
        eventName: "jkl",
        status: "upcoming"
    },
]

我想使用特定键的优先级数组对这些对象数组进行排序,例如 ["live", "upcoming", "completed"] 表示状态,这意味着所有实时事件首先出现,然后是即将到来的事件,然后是已完成的事件。互联网上的答案似乎只能使用键按升序或降序对数组对象进行排序。我该如何处理?

2 个答案:

答案 0 :(得分:6)

您可以使用带有排序数组的 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);

答案 1 :(得分:1)

您可以通过首先根据 status 对数组进行分组,然后在订单数组上使用 .flatMap() 来执行此操作,而无需对线性时间复杂度进行排序。对于有序数组中的每个值,您可以从 O(1) 中的分组中获取分组值(即:立即),并映射这些分组对象。当您使用 flatMap 时,这些分组的对象将被展平到结果数组中:

const eventList = [ { eventName: "abc", status: "completed" }, { eventName: "def", status: "live" }, { eventName: "ghi", status: "live" }, { eventName: "jkl", status: "upcoming" }, ];

const order = ["live", "upcoming", "completed"];
const grouped = eventList.reduce(
  (map, o) => map.set(o.status, (map.get(o.status) || []).concat(o)), new Map
);

const result = order.flatMap(status => grouped.get(status) || []);
console.log(result);