1

我有一个与将数据从一种形式转换为另一种形式相关的编程问题。

我有一个对象数组,表示需要将其转换为矩阵以进行可视化的数据表。我在教育期间以某种方式避免涉及矩阵数学,所以如果我的术语不正确,我深表歉意。


更具体地说,我有一个表示格式化数据的对象数组:

var pokes = [
    {source: "Harry", target: "Maria", type: "poke"},
    {source: "Brin", target: "Serge", type: "poke"},
    {source: "Maria", target: "Brin", type: "poke"},
    {source: "Serge", target: "Simon", type: "poke"},
    {source: "Brin", target: "Serge", type: "poke"}
];

我需要把它变成一个方阵以用于和弦图,例如:

var matrix = [
    [0, 5, 2, 1, 4],
    [7, 0, 8, 4, 7],
    [9, 4, 0, 3, 1],
    [8, 5, 5, 0, 8],
    [6, 3, 9, 2, 0]
];

结果矩阵的长度/宽度 n 等于数组中唯一个体的数量(Harry、Serge 等),相应单元格中的值 (x, y) 是人 x 戳人 y 的次数. pokes 数组中的每个对象都代表一个 poke(“type”属性不影响矩阵的构造)。


因此,例如,对象:

{source: "Brin", target: "Serge", type: "poke"}

将向代表 (Brin, Serge) 的单元格加 1。


这是我的伪代码方法:

Create array, people, containing list of unique people in pokes (both source and target).
Create empty array, matrix.
For each person in people:
    Create an array, foo, of size people.length.
    For each poke in pokes:  
        If person == poke.source:
            Add 1 to foo[x] where x is the index of poke.target in people.
    Push foo into matrix.

我还没有进入真正的代码,因为我不确定这个方法是:

  1. 正确的
  2. 高效/快速,尤其是当 pokes.length 接近数千时

任何意见,将不胜感激; 特别是如果 d3.js 有一个隐藏的方法来创建我没有发现的矩阵。

4

0 回答 0