Skip to content Skip to sidebar Skip to footer

Push One Array To The End Of Another

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

Solution 1:

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:

Solution 2:

This should probably work:

AR1.push(...AR2);

References :

Spread Syntax

Post a Comment for "Push One Array To The End Of Another"