【问题标题】:Javascript sort array of objects using array of priorityJavascript使用优先级数组对对象数组进行排序
【发布时间】:2021-04-14 03:26:59
【问题描述】:

我有这个对象数组:

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

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

【问题讨论】:

    标签: javascript node.js arrays sorting object


    【解决方案1】:

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

    【讨论】:

    • 我认为下面的例子很完美:-
    • @DarshanMalani 什么?
    • @Tibebes.M 我说下面的例子是完美的..
    【解决方案2】:

    您可以通过首先根据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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      相关资源
      最近更新 更多