Serge insas
Serge insas

Reputation: 46802

variables issue in GAS using array

I couldn't really find a good title for this question... sorry about that :-)

It should be something like : a simple question on something that really bothers me :

in this (very) basic code I'd like to keep the variable headers intact and it doesn't... why and how can get a simple way to keep that value unchanged when I modify the otherVersion ?

The sheet is a simple row of cells containing a,b,c,d,e,f,g,h,i,j in successive cells.

function myFunction() {
  var sh = SpreadsheetApp.getActive();
  var data = sh.getDataRange().getValues();
  var headers = data[0];
  Logger.log(headers);
  var otherVersion = data[0];
  var x = otherVersion.shift();
  Logger.log(x)
  Logger.log(headers);// why has it changed ?
}

Logger result :

 [a, b, c, d, e, f, g, h, i, j]
  a
 [b, c, d, e, f, g, h, i, j]

I need a 'normal' and a 'shifted version' of this header, that's why I use 2 different var names. Why this weird interaction ? what's the logic behind this ?

Upvotes: 0

Views: 81

Answers (1)

Srik
Srik

Reputation: 7967

In your code, data[0] is an array. Doing var otherVersion = data[0]; doesn't create a copy instead it works on the same copy. Use the slice() function instead.

var otherVersion = data[0].slice(0);

Upvotes: 1

Related Questions