如何按给定顺序在其他数组中对集合进行排序

时间:2019-05-29 08:42:42

标签: javascript angular typescript sorting

我有一个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"
    }
]

2 个答案:

答案 0 :(得分:0)

您可以将比较器传递给Array.sort,该比较器按index数组中children[0].id的{​​{1}}进行比较/排序

orderArray

答案 1 :(得分:0)

尝试一下:

var newdataArray = []

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

data = newdataArray