首页 > 解决方案 > Javascript使用优先级数组对对象数组进行排序

问题描述

我有这个对象数组:

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

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

标签: javascriptnode.jsarrayssortingobject

解决方案


您可以使用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);


推荐阅读