0

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

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

can i ask what happens to array2? we're no longer using it?
Your array 2 seems to be formatted correctly, so you don't need to transpose rows and columns if my understanding is correct.
aa okay. make sense. will try it out. thanks
i updated the question since im able to get the previous values in array2 in array1. hopefully this is clearer than before. just in case if you need to update anything.
So how is the script supposed to know that ['a'] and ['a1', 'a2'] are meant to be concatenated? Because it will always be the first and second row?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.