2

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]);

}
Marios
  • 26,333
  • 8
  • 32
  • 52
incher91
  • 27
  • 4

1 Answers1

2

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?

Marios
  • 26,333
  • 8
  • 32
  • 52
  • 1
    Hi Marios, thanks for your solution. This is exactly what i was searching for. I knew it must be something 'weird' :-) – incher91 Oct 14 '20 at 16:14