Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing 1D array into a sheet column in Apps Script

I'm trying to write a long 1D array into a column in a sheet using Apps Script but can't make it work. Have tried setValues() but it required a 2D array.

function writeArrayToColumn() {
var mainSheet = SpreadsheetApp.getActiveSheet()
var array = ["M", "C", "D", "F", "R", "S", "Q", "V", "G"]
var range = mainSheet.getRange(2, 1, array.length, 1)
range.setValue(array)
}

This writes only "M" in first 9 cells not "M" in 1, "C" in 2, so on and so forth. If I use setValues() I get an error:

Cannot convert Array to Object[][].

There are similar questions on Stack Overflow but none could answer this.

like image 675
mcansado Avatar asked Sep 19 '15 14:09

mcansado


People also ask

How do I declare an array in Google Apps Script?

Here is how you declare and initialize an array called colors . You list a number of values within square brackets ( [ and ] ). Arrays have an indexing system to help you access values stored at specific positions. The indexing system starts at 0 and not 1.

How do you write a spreadsheet in an app script?

To create a spreadsheet, use the create method on the spreadsheets collection, as shown in the following example. This example creates a blank spreadsheet with a specified title. // the built-in method SpreadsheetApp.


2 Answers

In addition to Sandy's explanation, adding in a map() function should also work.

function writeArrayToColumn() {
var mainSheet = SpreadsheetApp.getActiveSheet()
var array = ["M", "C", "D", "F", "R", "S", "Q", "V", "G"]
    .map(function (el) {
        return [el];
    });
var range = mainSheet.getRange(2, 1, array.length, 1)
range.setValues(array)
}
like image 100
JPV Avatar answered Nov 12 '22 04:11

JPV


I think you want to write new values to each row. So this is the code you need:

function writeArrayToColumn() {
  var mainSheet = SpreadsheetApp.getActiveSheet();
  var array = ["M", "C", "D", "F", "R", "S", "Q", "V", "G"];
  var outerArray = [],
      tempArray = [],
      i=0;

  for (i=0;i<array.length;i+=1) {
    tempArray = [];
    tempArray.push(array[i]);
    outerArray.push(tempArray);
  };

  var range = mainSheet.getRange(2, 1, array.length, 1);

  range.setValues(outerArray);
};

If you want to write the array to one row, where each array element will go into a new cell, create an outer array, and push the inner array into the outer array:

function writeArrayToColumn() {
  var mainSheet = SpreadsheetApp.getActiveSheet();
  var array = ["M", "C", "D", "F", "R", "S", "Q", "V", "G"];
  var range = mainSheet.getRange(2, 1, array.length, 1);
  var outerArray = [];
  outerArray.push(array);

  range.setValues(outerArray);
};

If you want to put each array element into a new row, that would be different. You'd need to loop through the array, and create a new array for every element.

like image 1
Alan Wells Avatar answered Nov 12 '22 05:11

Alan Wells