0

I am new to Google Scripts and I am doing my first project. I have to manage an array of arrays; in my case, it can be thought as a list of teams that changes with time.

I managed to isolate the problem in a simplified case that still exhibit the weird behaviour. Here is the code:

function check_push() {
  var andrea = [[]];
  ss = SpreadsheetApp.getActiveSpreadsheet();
  entra = ss.getRange('A1:A');
  for (var counter = 0; counter <= 2; counter = counter + 1) {
    ft = andrea[counter]
    ft.push(entra.getCell(counter+1,1).getValue())
    andrea.push(ft);
  }
  Logger.log(andrea);
}

If the first three elements A1, A2, A3 are el1, el2, el3, we expect to have an array of increasingly bigger teams:

[ [], [el1], [el1, el2], [el1, el2, el3] ]

However, the output is:

[[el1, el2, el3], [el1, el2, el3], [el1, el2, el3], [el1, el2, el3]]

In other words, the last push overwrites (!!) all the previous arrays. What's going on?

TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • It doesn't overwrite anything. It's just pushing to the very *same* array three times. – Bergi Jul 06 '22 at 14:34
  • Array in javascript are work by reference. Meaning that when you write `ft = andrea[counter]`, your not creating a copy of the array, just giving it a second name. Then, when you push, your are push to both `ft` and `andrea[counter]`. – B. Mélicque Jul 06 '22 at 14:35
  • Nice. I am used to C. How do I create a copy of an array then? – Andrea Marino Jul 06 '22 at 15:05

0 Answers0