Return a specific row of a 2D array and write into Range

Viewed 46

I have a problem with my array in Google Script. I want to return for example only the first row of my 2D array. I tried it with adding '[0]' to get the first row of the array but it doesnt work. My desired output should be A30 = Lisa, B30 = 1, C30 = 1991

function testArray() {

var sht_test = SpreadsheetApp.getActive().getSheetByName('Test');
var myArray = [
    ['Lisa',1,1991],
    ['Tim', 2,1989]
  ];

sht_test.getRange('A20:C21').setValues(myArray);  // returning the complete array works

//this doesnt work...
sht_test.getRange('A30:C30').setValues(myArray[0]);

}
1 Answers

Issue / Explanation:

setValues() accepts a 2D array like myArray:

var myArray = [
    ['Lisa',1,1991],
    ['Tim', 2,1989]
  ];

However, myArray[0] will give you a 1D array:

['Lisa',1,1991]

To make it 2D, simply wrap it up with []:

[['Lisa',1,1991]]

It may seem weird, but you must make it 2D because this is what setValues() accepts.


Solution:

Use this instead:

sht_test.getRange('A30:C30').setValues([myArray[0]]);

Highly Related:

What does the range method getValues() return and setValues() accept?

Related