【问题标题】:Javascript categorical object array sorting [duplicate]Javascript分类对象数组排序[重复]
【发布时间】:2020-07-25 18:19:49
【问题描述】:

假设我有一个对象数组:

let array = [

    {id: 0, type: "Office" },
    {id: 1, type: "Security" },
    {id: 2, type: "Office" },
    {id: 3, type: "Security" },
    {id: 4, type: "Security" },
    {id: 5, type: "Office" },
    {id: 6, type: "Agent" },
    {id: 7, type: "Security" }

];

我需要根据自定义的分类序列集进行排序,即["Office", "Agent", "Security"] 得到以下输出:

var array = [
    {id: 0, type: "Office" },
    {id: 2, type: "Office" },
    {id: 5, type: "Office" },
    {id: 6, type: "Agent" }
    {id: 1, type: "Security" },
    {id: 3, type: "Security" },
    {id: 4, type: "Security" },
    {id: 7, type: "Security" }
];

没有找到任何合适的解决方案。

【问题讨论】:

    标签: javascript sorting object categories


    【解决方案1】:

    您可以使用indexOf 获取排序顺序。

    let array = [
        {id: 0, type: "Office" },
        {id: 1, type: "Security" },
        {id: 2, type: "Office" },
        {id: 3, type: "Security" },
        {id: 4, type: "Security" },
        {id: 5, type: "Office" },
        {id: 6, type: "Agent" },
        {id: 7, type: "Security" }
    ];
    const order = ["Office", "Agent", "Security"]
    array.sort((a,b)=>order.indexOf(a.type)-order.indexOf(b.type));
    console.log(array);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2021-03-11
      • 2017-10-04
      • 2012-12-10
      相关资源
      最近更新 更多