【问题标题】:How can I sort a collection based in the given order in other array [duplicate]如何根据其他数组中的给定顺序对集合进行排序[重复]
【发布时间】:2019-10-14 19:44:07
【问题描述】:

我有一个 ibject 数组,每个元素内部都有另一个对象,例如

data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

] 

我想通过children.id 值对整个集合进行排序,但要基于另一个数组给出的顺序

orderArray = [3, 1, 2] 

所以输出将是

data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]

【问题讨论】:

    标签: javascript angular typescript sorting


    【解决方案1】:

    您可以将 比较器 传递给 Array.sort,它在 orderArray 数组中按 indexchildren[0].id 进行比较/排序

    let data = [{name:"A",type:"AA",children:[{id:1,name:"Child-A",admin:["Y"]}],other:"NA"},{name:"B",type:"BB",children:[{id:2,name:"Child-B"}],other:"NA"},{name:"C",type:"CC",children:[{id:3,name:"Child-C"}],other:"NA"}];
    let orderArray = [3, 1, 2];
    
    data.sort((a,b) => orderArray.indexOf(a.children[0].id) - orderArray.indexOf(b.children[0].id));
    console.log(data);

    【讨论】:

      【解决方案2】:

      试试这个:

      var newdataArray = []
      
      orderArray.forEach(index => {
          newdataArray.push(data[index - 1])
      });
      
      data = newdataArray
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 2013-12-24
        • 2014-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多