Home > Enterprise >  Google Sheet Script - Combining two 2d arrays
Google Sheet Script - Combining two 2d arrays

Time:02-27

I've got a sheet which pulls data from an API, formats it nicely into an array, then writes the array to a sheet.

However the API only allows a certain number of items to be queried at a time, so I've got a loop that is running the API call several times and then writing to sheet.

using multiple setvalues commands to write the data is a bit slow, and I was thinking of having a "Master" array that I can append the results to in each loop, then just write the Master array to the sheet once.

Which I'm hoping will help improve performance.

However I can't find any information on how to merge arrays together.

E.g. I've declared my large array

var fullDataArray=new Array(new Array())

And I have a dataArray that is being populated by my API call

enter image description here

Other than using splice and appending the data row by row, is there a way to append dataArray to fullDataArray?

CodePudding user response:

Description

You can use the Array.concat method. It is always advised not to use new Array() and instead use []. In your case use var fullDataArray=[[]];

Script

function test5() {
  try {
    var a = [[1,2],[3,4],[5,6]];
    var b = [[7,8],[9,10]];
    var c = a.concat(b)
    console.log(c);
  }
  catch(err) {
    console.log(err);
  }
}

Console.log

6:53:15 AM  Notice  Execution started
6:53:18 AM  Info    [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
6:53:16 AM  Notice  Execution completed

Reference

  • Related