Complex d3.nest() manipulation

前端 未结 4 1756
清歌不尽
清歌不尽 2020-12-30 08:21

I have an array of arrays that looks like this:

var arrays = [[1,2,3,4,5],
              [1,2,6,4,5],
              [1,3,6,4,5],
              [1,2,3,6,5],
          


        
4条回答
  •  忘掉有多难
    2020-12-30 09:02

    Since d3-collection has been deprecated in favor of d3.array, we can use d3.groups to achieve what used to work with d3.nest:

    var input = [
      [1, 2, 3, 4, 5],
      [1, 2, 6, 4, 5],
      [1, 3, 6, 4, 5],
      [1, 2, 3, 6, 5],
      [1, 7, 5],
      [1, 7, 3, 5]
    ];
    
    function process(arrays, depth) {
      return d3.groups(arrays, d => d[depth]).map(x => {
        if (
          x[1].length > 1 ||                     // if there is more than 1 child
          (x[1].length == 1 && x[1][0][depth+1]) // if there is 1 child and the future depth is inferior to the child's length
        )
          return ({
            "label": x[0],
            "children": process(x[1], depth+1)
          });
        return ({ "label": x[0] });              // if there is no child
      });
    };
    
    console.log(process(input, 0));

    This:

    • Works as a recursion on the arrays' depths.
    • Each recursion step groups (d3.groups) its arrays on the array element whose index is equal to the depth.
    • Depending on whether there are children or not, the recursion stops.

    Here is the intermediate result produced by d3.groups within a recursion step (grouping arrays on there 3rd element):

    var input = [
      [1, 2, 3, 4, 5],
      [1, 2, 6, 4, 5],
      [1, 2, 3, 6, 5]
    ];
    
    console.log(d3.groups(input, d => d[2]));

提交回复
热议问题