Search code examples
javascriptarraysgoogle-apps-scripttranspose

JavaScript / Google Script - Transpose "Row" Array into "Column" Array


Good afternoon,

I am attempting transpose a "row" array (or 1D array) into a "column" array (or array that is one array containing individual arrays within it) to allow me to set values to a single column (downward multiple rows) instead if it being one row across multiple columns

I attempted using a push loop and a map function but neither attempt succeeded:

function myFunction2() {

  var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Source1");

  var lastColumn = ss.getLastColumn()

  var endRange = lastColumn-3

  //Retrieve values into array named "items"
  var items = ss.getRange(16,4,1,endRange).getValues()

Transpose attempt # 1:

  var colArray = [];
    for (var i=0; i<items.length; i++)
    {
      colArray.push([items[i]]);
    }
}

Output for Attempt # 1:

[[[item1, item2, item3, item4, item5]]]

Transpose attempt # 2:

  var colArray = items.map(function (el){
      return [el];
  });

Output for attempt # 2:

[[[item1, item2, item3, item4, item5]]]

The intended output I would like to have is:

[[item1], [item2], [item3], [item4], [item5]]

Would there be a way to achieve the intended output?


Solution

  • In your script of var items = ss.getRange(16,4,1,endRange).getValues(), items is 2 dimensional array like [[value1, value2, value3,,,]]. So, when your script is modified, it becomes as follows.

    From:

      var colArray = [];
        for (var i=0; i<items.length; i++)
        {
          colArray.push([items[i]]);
        }
    }
    

    To:

    var colArray = [];
    for (var i = 0; i < items[0].length; i++) {
      colArray.push([items[0][i]]);
    }
    

    And,

    From:

    var colArray = items.map(function (el){
        return [el];
    });
    

    To:

    var colArray = items[0].map(function (el){
      return [el];
    });
    

    Note:

    • Or, when you want to transpose the values including the several rows and columns, you can also use the following script.

        const colArray = items[0].map((_, i) => items.map(row => row[i]));
      

    References: