-1

Calling the following lines of code in Google Apps Script causes an error:

    var newSheetData = [[]]; newSheetData[1][1] = "1";

However, when these lines of code are called, no error is thrown:

        var newSheetData = [[]]; newSheetData[0][1] = "1";

This means there is only one row defined in the 2d array according to the way I've defined it.

This is the only way I am aware of for declaring a 2d array in Google Apps Script.

How might I create a mutable 2d array of generic dimensions (as many as needed,) or even pre-define the size of a 2d array in Google Apps Script?

  • 2
    Are these threads useful for your situation? https://stackoverflow.com/q/966225/7108653 https://stackoverflow.com/q/49354354/7108653 – Tanaike Mar 09 '20 at 02:29
  • Yes- for some reason my searches didn't come across these threads. – Jaden Ranzenberger Mar 09 '20 at 04:45
  • Does this answer your question? [Javascript: How to initialize a 2 dimensional array](https://stackoverflow.com/questions/49354354/javascript-how-to-initialize-a-2-dimensional-array) – TheMaster Mar 09 '20 at 07:27

1 Answers1

2

In newSheetData[1][1] = "1";, newSheetData[1] is undefined. So cant access.

You can initialise 2d arrays some thing like below before using. Alternate method ES6 may not work in google app scripts.

const arr2dFill = (rows, cols, filler) => {
  const arr = new Array(rows);
  for (var i = 0; i < rows; i++) {
    arr[i] = [];
    for (var j = 0; j < cols; j++) {
      arr[i][j] = filler;
    }
  }
  return arr;
};

const arr2dFillEs6 = (rows, cols, filler) =>
  Array.from({ length: rows }, () => new Array(cols).fill(filler));

var arr1 = arr2dFill(3, 3, "1");
var arr2 = arr2dFillEs6(3, 3, "2");

arr1[1][1] = "3";
arr2[1][1] = "4";

console.log(arr1);
console.log(arr2);
Siva K V
  • 10,561
  • 2
  • 16
  • 29