Re-arrange array range

161 views
Skip to first unread message

Keith Andersen

unread,
Jul 3, 2023, 2:16:04 PM7/3/23
to google-apps-sc...@googlegroups.com
If I get the values A1:A10 (horizontal range) and put them in an 2d array, app script will not allow me to set that array to a vertical range.

Is there a way in app script to re-arrange the array so as to be able to set to an array opposite the range it was collected? It would obviously have the same number of arrays and array elements.

Tks in advance.
Keith

Zack Reynolds

unread,
Jul 3, 2023, 3:03:10 PM7/3/23
to google-apps-sc...@googlegroups.com
So you have to pivot the array. Here are some quick examples:

function transposeArrays(){

    let ss = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = ss.getSheetByName('Data');

    // pivot single column array from vertical to horizontal
    let vData = sheet.getRange("A1:A10").getValues().flat();
    let newHData = [];
    vData.forEach(e => { newHData.push(e) });

    // pivot single row array from horizontal to vertical
    let hData = sheet.getRange("A1:J1").getValues().flat();
    let newVData = [];
    hData.forEach(e => { newVData.push([e]) });

    // switch rows & columns on full range
    let fData = sheet.getRange("A1:D4").getValues();
    let newFData = fData[0].map((col, i) => fData.map(row => row[i]));

}


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/CAJ8MD4x1Ee8k-Ngo1yKtXnz94oMRWY6svt2BTtJen7nPqAfEsg%40mail.gmail.com.

Keith Andersen

unread,
Jul 3, 2023, 3:30:52 PM7/3/23
to google-apps-sc...@googlegroups.com
Thanks Zack - I'll give that a try

Keith 

Keith Andersen

unread,
Jul 4, 2023, 12:02:49 AM7/4/23
to google-apps-sc...@googlegroups.com
Worked fine. Much thanks!
Keith 
Reply all
Reply to author
Forward
0 new messages