2
votes

I have a two-dimensional array in Google apps script that contains arrays of different lengths. I would like to set the values of the array in a spreadsheet. However, because the arrays inside it are different lengths, I receive an error that essentially says the range and the array height don't line up. I've listed an example of the structure of the array below.

I can make it work if I add empty values to each individual array so that they all match the length of the longest array. This seems like a workaround though. Is there another way that I can set the values of the two-dimensional array?

var array = [
  [a],
  [b,c],
  [d,e],
  [],
  [f,g,h,i],
  [],
  [j,k],
  ]
2

2 Answers

4
votes

No, you cannot. The dimensions must match.

What you can do if you have few "rows" with great length difference, is to set each row on it's own.

for( var i = 0; i < array.length; ++i )
  sheet.getRange(i+1, 1, 1, array[i].length).setValues([array[i]]);

But that's just another workaround. But working on your array to make all lengths match and do a single setValues will probably perform better.

2
votes

In case your real array has many rows, individual writes will be expensive. Redimensioning each row array is fairly straightforward due to the way js handles arrays. A pattern similar to one i use is:

function myFunction() {
 var array = [
  [1],
  [2,2],
  [3,5],
  [],
  [0,0,0,0],
  [],
  [0,0],
 ];

 // get length of the longest row
 var max = array
  .slice(0)
  .sort(function (a,b) {
    return ( (a.length !== b.length) ? 1 : 0 );
  })[0].length;

 // arrays are zero indexed
 var maxi = max-1;

 // insert a pointer at max index if none exists
 array = array
  .map(function (a){ 
    a[maxi] = a[maxi] || ""; 
    return a; 
  });

 Logger.log(array);
}