2

I am new to GAS. I have two arrays. AR1 has 7 cols and 16 rows. AR2 has 7 cols and 4 rows. I want to push the small array (AR2) to the bottom of the big array (AR1) for AR1 to have 7 cols and 20 rows. This is my code:

AR1.push(AR2);

When I check if there is new data by setting the values of AR1 into the active sheet (sh):

sh.getRange(1,1,AR1.length,AR1[0].length).setValues(AR1)

I get an error: Exception: The number of columns in the data does not match the number of columns in the range. The data has 4 but the range has 7. And AR1 is written in the unchanged form in the active sheet with 7 cols and 16 rows.

It looks like AR2 is transposed in push command and/or not pushed to the end of AR1, but I don't understand why or how to fix it. Any help is highly appreciated.

Mike B.
  • 99
  • 3
  • 9

2 Answers2

3

Modification points:

  • I think that the reason of your issue is to push 2 dimensional array to the array.
    • For example, it supposes that the following 2 dimensional arrays are merged using push().

        var ar1 = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]];
        var ar2 = [["a4", "b4", "c4"],["a5", "b5", "c5"]];
        ar1.push(ar2)
        console.log(ar1)
      
    • The result is as follows. You can see ar2 is added to ar1. But this cannot be used for setValues(ar1). This is directly the reason of your issue.

        [
            ["a1","b1","c1"],
            ["a2","b2","c2"],
            ["a3","b3","c3"],
            [["a4","b4","c4"],["a5","b5","c5"]]
        ]
      

In order to avoid this issue, I would like to propose the following modification.

Modified script:

From:
AR1.push(AR2);
To:
AR1 = AR1.concat(AR2);

or

AR1 = [...AR1, ...AR2];

or

Array.prototype.push.apply(AR1, AR2);
  • By this modification, when above sample values of ar1 and ar2 are used, the following result is obtained. By this modification, I think that your script of sh.getRange(1,1,AR1.length,AR1[0].length).setValues(AR1) also works.

      [
          ["a1","b1","c1"],
          ["a2","b2","c2"],
          ["a3","b3","c3"],
          ["a4","b4","c4"],
          ["a5","b5","c5"]
      ]
    

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
1

This should probably work:

AR1.push(...AR2);

References :

Spread Syntax

Marios
  • 26,333
  • 8
  • 32
  • 52