使用另一个数组的对象属性对数组进行排序

时间:2018-05-19 18:12:03

标签: javascript arrays

我现在有一个令人困惑的问题。情况是这样的:

let example = [
  {
    name: "First",
    id: 1,
    rank: 1,
    childs: [5,3] // [3,5] -> wrong, because the element which have the id: 3 
//(First's second child), have the rank 2, but with id: 5 (First's first child) have the rank 1.
  },
  {
    name: "First's first child",
    id: 5,
    rank: 1,
    childs: [4,2]
  },
  {
    name: "First's second child",
    id: 3,
    rank: 2,
    childs: [6]
  },
  {
    name: "Second's first child",
    id: 4,
    rank: 1,
    childs: []
  },
  {
    name: "Second's second child",
    id: 2,
    rank: 2,
    childs: []
  },
  {
    name: "Third's first child",
    id: 6,
    rank: 1,
    childs: []
  }
]

childs属性是一个数组,显示元素的子ID(项的名称显示元素之间的关系)。 childs数组的元素顺序必须与childs具有相同ID的元素排名相等。 这里的问题是,childs数组的排序并不总是正确的,这给我带来了很多问题。我需要做的是获取元素的子元素(数组的childs项表示项目在example中的id),在{{1}中搜索它们中的每一个}}数组,然后按example中的排名顺序对childs数组进行排序。因此,我想对example进行排序,具体取决于example[i].childs中相同的ID&#39项目排名。这怎么可能?

1 个答案:

答案 0 :(得分:1)

如果我正确理解了OP,则输出是OP示例,注释是输入。 childs属性的排序基于相应元素的排名来自“父”的childs数组中的ID。如果这是正确的,那么您可以使用find在数组中搜索与子ID匹配的元素,根据它们的排名对它们进行排序,然后将child属性替换为新的排序值。

// First map over the entire example
const sorted = example.map(({childs, ...p}) => ({
  // Copy all of the original element's properties except `childs`
  ...p,
  // Replace `childs` with a sorted array
  childs: childs
    // Find the child element based on the ID
    .map((pid) => example.find(({id: cid}) => pid === cid))
    // Sort the elements based on their rank
    .sort(({rank: a}, {rank: b}) => a - b)
    // Pick out only the `id` value
    .map(({id} = {}) => id)
}));

一个有效的例子:

const example = [{
  name: "First",
  id: 1,
  rank: 1,
  childs: [3, 2]
},
{
  name: "First's first child",
  id: 2,
  rank: 1,
  childs: [4, 5]
},
{
  name: "First's second child",
  id: 3,
  rank: 2,
  childs: [6]
},
{
  name: "Second's first child",
  id: 4,
  rank: 1,
  childs: []
},
{
  name: "Second's second child",
  id: 5,
  rank: 2,
  childs: []
},
{
  name: "Third's first child",
  id: 6,
  rank: 1,
  childs: []
}
];

const sorted = example.map(({childs, ...p}) => ({
  ...p,
  childs: childs
    .map((pid) => example.find(({id: cid}) => pid === cid))
    .sort(({rank: a}, {rank: b}) => a - b)
    .map(({id} = {}) => id)
}));
console.log(sorted);