Home > Enterprise >  How to combine 3 multidimentional arrays using GAS?
How to combine 3 multidimentional arrays using GAS?

Time:05-04

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.

thank you!

CodePudding user response:

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

CodePudding user response:

Maybe something like that

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

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

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

const arrays = [array1, array2, array3]

const res = arrays.reduce((acc, [cols, data]) => [[...acc[0], ...cols], [...acc[1], ...data]], [[], []])

CodePudding user response:

function myFunction() {
  let a1 = [["Col1", "Col2", "Col3"], ["Data1", "Data2", "Data3"]];
  let a2 = [["Col5", "Col10", "Col21"], ["Data5", "Data10", "Data21"]];
  let a3 = [["Col8", "Col11"], ["Data8", "Data11"]];
  Logger.log([[...a1[0],...a2[0],...a3[0]],[...a1[1],...a2[1],...a3[1]]]);
}
  • Related