D3.js - 合并两个邻接矩阵 D3/JS

D3.js - merge two adjacency matrices in ones with D3/JS

我想合并 2 个邻接矩阵 d3.js。举个例子:

矩阵 1:

{
    "nodes":[
        {
            "id": a,
            "year": 1
        },{
            "id": b,
            "year": 1
        },
        {
            "id": c,
            "year": 1
        }
    ],
    "links":[
        {
            "source": a,
            "target": b
        },
        {
            "source": a,
            "target": c
        }
    ]
}

矩阵 2:

{
    "nodes":[
        {
            "id": a,
            "year": 2
        },{
            "id": b,
            "year": 2
        },
        {
            "id": d,
            "year": 2
        }
    ],
    "links":[
        {
            "source": a,
            "target": b
        },
        {
            "source": a,
            "target": d
        }
    ]
}

如您所见,一些 ID 出现在两个矩阵中,例如 a 和 b。我想将这个单元格合并到两个矩阵中,并更改这个单元格的颜色。 有人可以给我一些解决这个问题的想法吗?

结果一定是这样的:

{
    "nodes":[
        {
            "id": a,
            "year": 3
        },{
            "id": b,
            "year": 3
        },
        {
            "id": c,
            "year": 1
        },
                {
            "id": d,
            "year": 2
        }
    ],
    "links":[
        {
            "source": a,
            "target": b
        },
        {
            "source": a,
            "target": c
        },
        {
            "source": a,
            "target": d
        }
    ]
}

因此,据我了解,您需要做什么(合并并突出显示重复节点,基于重复邻接,而不是 id),您可以这样做:

  • 遍历 links 的组合数组以找出 unique/duplicate 个条目(同时考虑反向 source/target
  • 遍历 nodes 的组合数组并用 year:3 标记那些属于重复链接的节点
  • 构建 linksnodes
  • 的结果对象

const m1 = {"nodes":[{"id":'a',"year":1},{"id":'b',"year":1},{"id":'c',"year":1}],"links":[{"source":'a',"target":'b'},{"source":'a',"target":'c'}]},
      m2 = {"nodes":[{"id":'a',"year":2},{"id":'b',"year":2},{"id":'d',"year":2}],"links":[{"source":'a',"target":'b'},{"source":'a',"target":'d'}]},
      
      links = [...m1.links, ...m2.links].reduce((r,l) => {
        const dup = r.find(({source:s, target: t}) => 
          (s == l.source && t == l.target) || 
          (s == l.target && t == l.source))
        dup ? dup.dup = true : r.push(l)
        return r
      }, []),
      
      nodes = [...m1.nodes, ...m2.nodes].reduce((r,n) => {
        const dupL = links.find(l => 
          l.dup && (l.source == n.id || l.target == n.id)),
              dupN = r.find(({id}) => id == n.id)
        !dupN && r.push({...n, ...(dupL && {year: 3})})
        return r
      }, []),
      
      mergedMatrix = {links:links.map(({dup,...rest}) => rest),nodes}
     
console.log(mergedMatrix)
.as-console-wrapper{min-height:100%;}