tiredqa_18
tiredqa_18

Reputation: 331

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

Upvotes: 0

Views: 59

Answers (2)

So... basically your are organising your data as [[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);

Upvotes: 1

ziganotschka
ziganotschka

Reputation: 26796

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]; });
      });
  }
  

Upvotes: 0

Related Questions