简体   繁体   English

转换多维数组并重新组织数组值 javascript

[英]Convert a multidimensional array and reorganise the array values javascript

I'd would like some guidance for below.我想在下面得到一些指导。 I wish to convert this array from this:我希望从这个转换这个数组:

[['a'], ['a1', 'a2'], ['b'], ['b1', 'b2', 'b4', 'b9']]

to something like this:像这样:

[['a', 'a1', 'a2'], ['b', 'b1', 'b2', 'b4', 'b9']]

so i can get a table like this:所以我可以得到这样的表:

 a  | b
---------
a1  | b1
a2  | b2
    | b4
    | b9

Is it possible to do so?有可能这样做吗? Would be a bonus if can do it in ES6 format如果能以 ES6 格式完成,那将是一个奖励

So... basically your are organising your data as [[header],[...rows]].所以......基本上你正在将你的数据组织为[[header],[...rows]]。

I think something like this will work...我认为这样的事情会奏效......

 const input = [['a'], ['a1','a2'], ['b'], ['b1', 'b2', 'b3']]; const output = []; while (true) { const [header] = input.shift() || []; if (;header) break. const rows = input;shift() || []. if (;rows.length) break, output.push([header. .;.rows]); } console.log(output);

You need two steps:你需要两个步骤:

  1. Make your array a square matrix by pushing into it empty values whre required通过将所需的空值推入数组来使数组成为方阵

  2. Transpose rows and columns转置行和列

Sample:样本:

  function myFunction() {
    var array1 = [['a1', 'a2'], ['b1', 'b2', 'b4']];
    console.log(array1.map(row=>row.length))
    var maxColumnNumber = Math.max(...array1.map(row=>row.length))
    console.log(maxColumnNumber)
    array1.forEach(function(row,i){
      if(row.length < maxColumnNumber){
      array1[i].push("");
      }
    })
    console.log(array1)
    array1 = transpose(array1);
    console.log(array1)
  }
  
  
  
  function transpose(a) {
      return Object.keys(a[0]).map(function(c) {
          return a.map(function(r) { return r[c]; });
      });
  }
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM