Search code examples
javascriptarraysgoogle-apps-scriptmap-function

Google Scripts: Getting an array [ [x], [y] ] of nth length to return array of x/y values [ [x1,y1], [x2,y2], etc]


I have an array:

var array1 = [ ["Item1","Item2","Item3","Item4"], ["ItemA","ItemB","ItemC","ItemD"] ];

Trying to get it set up in pairs to read:

[ ["Item1", "ItemA"], ["Item2", "ItemB"], ["Item3", "ItemC"], ["Item4", "ItemD"] }

I've been able to successfully do this by outputting the original array on a sheet, using the following 'transpose' function (found on this site) and then doing another getDataRange().getValues() call on the newly transposed sheet.

function transpose(destSheet) {

  var values = destSheet.getDataRange().getValues; 
  var values = range.getValues();

  // transpose it & write it out
  destSheet.getRange(1,1,values[0].length,values.length)
    .setValues(Object.keys(values[0]).map ( function (columnNumber) {
      return values.map( function (row) {
        return row[columnNumber];
      });
    }));
  
}

New to GAS so I've been frying my brain online trying to find an example of the map function to do on the array itself without having to paste it first to a sheet.


Solution

  • As I mentioned in my comment, I am not quite sure what you are trying to achieve from Google Apps Script prespective.

    However, here is the javascript part that you need to accomplish your goal:

    const array1 = [
    ["Item1","Item2","Item3","Item4"], 
    ["ItemA","ItemB","ItemC","ItemD"]
    ];
    const farray1 = array1[0].map((_, col) => array1.map(r => r[col]));
    console.log(farray1);