Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-apps-script-editor

Google Sheets App Script: Can you write an array to a single row instead of a single column?


The method .setValues() will take an array [[0],[1],[2],[3]] and write it to the .getRange() which has to be in multiple rows in a single column: A1, A2, A3, A4.

Instead, I want to write the same array but write it to a single row: A1, B1, C1, D1. Is this possible or do I have to rearrange my arrays to always write to a single column?

Edit: I'm sorry I think I was unclear. I am basically looking for a method or something similar to the appendRow method using an array. The array can be 1D or 2D (I can easily write a loop to create either). The reason appendRow doesn't work for me is because this method will place the array at the bottom of the data. I would like to place the row of data in a range I can specify.

For example, using the array above, I would like to write that array to getRange(1,4,1,4) with data already existing in getRange(1,3,10,10).


Solution

  • Try this

    function getData() {
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      //  var dataArray = ss.getRange(1, 1, ss.getLastRow(), 1).getValues();
      var dataArray = [[0],[1],[2],[3]]
      var dataUnit;
      var data = [];
      for (var i = 0; i < dataArray.length; i++) {
        dataUnit = dataArray[i].toString();
        data.push(dataUnit);
      }
      ss.appendRow(data);
    }