首页 > 解决方案 > 匹配对象数组中的 2 个属性的值并根据第三个属性的值过滤匹配项

问题描述

我有一个可以连接到多个其他节点的节点图。

每个节点代表一个数组中的一个对象。在每个节点的对象中都有一个数组,其中包含链接到该节点的所有节点的 id 及其深度:

 nodes: [
    {"id":1, "depth":0, "next":[], "children":[2, 3]},     // nodes.next = [2, 3]
    {"id":2, "depth":1, "next":[], "children":[1, 4, 5]},  // nodes.next = [4, 5]
    {"id":3, "depth":1, "next":[], "children":[1, 6, 7]},  // nodes.next = [6, 7]
    {"id":4, "depth":2, "next":[], "children":[2, 8]},     // nodes.next = [8]
    {"id":5, "depth":2, "next":[], "children":[2, 9]}      // nodes.next = [9]
] 

我想从某个节点遍历图形。

问题是节点的子数组包含链接到它的所有节点。深度为 2 的节点指向深度为 1 的节点。

所以我想在节点的对象中创建一个新数组,假设nodes.next并摆脱指向深度低于自身的节点的子节点。

真正让我困惑的部分是检查nodes.children. 我什至没有靠近我可能会检查节点深度nodes.children是否高于nodes[i].depth并推nodes[i].children[i]nodes[i].next.

如果有更好的方法来解决这个问题,我很高兴知道。我的尝试在很多方面都没有结果:

let childDepth;
for (let i = 0; i < nodes.length; i++) {
    for (let child in nodes[i].children) {
        if (nodes.id === child) {
            childDepth = nodes[i].depth;
        }
        if (childDepth > graph.nodes[i].depth) {
            nodes[i].next.push(child)
        }
    }
}

更新数组:

const nodes = [
    { "id": 37, "depth": 0, "children": [210, 395, 265], "next": [] },
    { "id": 210, "depth": 1, "children": [37, 260, 259, 391],"next": [] },
    { "id": 256, "depth": 2, "children": [265], "next": [] },
    { "id": 259, "depth": 2, "children": [210, 397, 396], "next": [] },
    { "id": 260, "depth": 2, "children": [210], "next": [] },
    { "id": 265, "depth": 1, "children": [37, 256, 388, 394, 271, 269], "next": [] },
    { "id": 269, "depth": 2, "children": [265], "next": [] },
    { "id": 271, "depth": 2, "children": [265], "next": [] },
    { "id": 388, "depth": 2, "children": [265], "next": [] },
    { "id": 391, "depth": 2, "children": [210], "next": [] },
    { "id": 394, "depth": 2, "children": [265], "next": [] },
    { "id": 395, "depth": 1, "children": [37], "next": [] },
    { "id": 396, "depth": 3, "children": [259, 413], "next": [] },
    { "id": 397, "depth": 3, "children": [259], "next": [] },
    { "id": 413, "depth": 4, "children": [396], "next": [] }
];

在此处输入图像描述

标签: javascriptarraysalgorithm

解决方案


请看看下面的代码,看看它是否是你要找的

const array = [
  {id:1, depth:0, next:[], children:[2, 3]},
  {id:2, depth:1, next:[], children:[1, 4, 5]},  
  {id:3, depth:1, next:[], children:[1, 6, 7]},  
  {id:4, depth:2, next:[], children:[2, 8]},    
  {id:5, depth:2, next:[], children:[2, 9]}
]

array.forEach(x => {
  let { children, depth } = x;

  for(let i=depth; i< children.length; i++){
    x.next.push(children[i]);
  }
});

输出如下:

[
  {"id":1,"depth":0,"next":[2,3],"children":[2,3]},
  {"id":2,"depth":1,"next":[4,5],"children":[1,4,5]}, 
  {"id":3,"depth":1,"next":[6,7],"children":[1,6,7]}, 
  {"id":4,"depth":2,"next":[],"children":[2,8]},
  {"id":5,"depth":2,"next":[],"children":[2,9]}
]

推荐阅读