1

I'm trying to push strings to a 2D array in Google Apps Script but I'm experiencing some weird behaviour I don't understand. A simplified version that produces the same behaviour is here:

function arrayTest() {
  var mainArr, subArr, i, arrLoc;
  mainArr = [];
  subArr = [];
  for (i = 0; i < 5; i++) {
    mainArr.push(subArr);
  }
  for (i = 0; i < 10; i++) {
    arrLoc = Math.floor(Math.random() * 5);
    mainArr[arrLoc].push('test');
  }
  Logger.log(mainArr);
}

What I would expect is for 'test' to be pushed into whichever array is at the index the Math functions generate - so if the numbers generated were say 0, 2, 1, 4, 4, 3, 0, 2, 1, 0 I thought I would receive:

[['test', 'test', 'test'], ['test', 'test'], ['test', 'test'], ['test'], ['test', 'test']]

However, this is not the case. What I instead receive is this:

[['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test'], 
 ['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test']]

It's clear that 'test' is being pushed to each position in the mainArr at each step of the for loop, rather than just the array that is at the index generated by the Math function.

Is there something blindingly obvious I'm missing here, such as an incorrect operator, or have I misunderstood how arrays work? Some guidance would be muchly appreciated!

Thanks.

chrisbib
  • 25
  • 3
  • Does this answer your question? [Copy array by value](https://stackoverflow.com/questions/7486085/copy-array-by-value) – TheMaster Jul 27 '20 at 13:34

1 Answers1

0

That's because you are pushing the same array into the main array over and over.

function arrayTest() {
  var mainArr, subArr, i, arrLoc;
  mainArr = [];
  subArr = []; // <-- This creates an array and stores it in the variable 'subArr'
  for (i = 0; i < 5; i++) {
    mainArr.push(subArr); // <-- The very same array is pushed into mainArr over and over
  }
  ...
}

But what I think you want is to create multiple arrays and push them into mainArr individually, so your code should look like this:

function arrayTest() {
  var mainArr, subArr, i, arrLoc;
  mainArr = [];
  for (i = 0; i < 5; i++) {
    subArr = []; // <-- Here you create a brand new array and stores it in 'subArr'
    mainArr.push(subArr); // <-- The newly created array is pushed into 'mainArr'
  }
  ...
}
Pedro Lima
  • 1,576
  • 12
  • 21