Search code examples
javascriptgoogle-apps-script

How to combine 3 multidimentional arrays using GAS?


I got prepared 3 arrays, which I'd like to combine into one:

let array1 = 
[
 ["Col1", "Col2", "Col3"],
 ["Data1","Data2","Data3"]
]

let array2 = 
[
 ["Col5", "Col10", "Col21"],
 ["Data5","Data10","Data21"]
]

let array3 = 
[
 ["Col8", "Col11"],
 ["Data8","Data11"]
]

How can I make it like this?

resultingArray = 
[
 ["Col1", "Col2", "Col3","Col5", "Col10", "Col21","Col8", "Col11"],
 ["Data1","Data2","Data3","Data5","Data10","Data21","Data8","Data11"]
]

where order of the columns doesn't matter.

I've tried using push(), ... the spread operator and concat(), but I haven't been able to apply it properly.


Solution

  • Description

    You can Array.concat each row of the 3 arrays into 1 row.

    Script

    let combined = array1.map( (row,i) => row.concat(array2[i],array3[i]) );
    console.log(combined);          
    

    Console.log

    12:12:18 PM Notice  Execution started
    12:12:19 PM Info    [ [ 'Col1', 'Col2', 'Col3', 'Col5', 'Col10', 'Col21', 'Col8', 'Col11' ],
      [ 'Data1',
        'Data2',
        'Data3',
        'Data5',
        'Data10',
        'Data21',
        'Data8',
        'Data11' ] ]
    12:12:18 PM Notice  Execution completed
    

    Reference