0

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 ?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution, however something is still unclear to me : when I refer to this doc it says the splice is used to add/remove part of an array and that a second parameter is required to tell how many item to remove... but here I don't remove anything (wich is a good thing for me in this case :) and you use only 1 parameter. So something must be missing in the mentioned doc... can you explain ? thanks in advance.
Serge, splice() and slice() are different functions :) See w3schools.com/jsref/jsref_slice_array.asp for more info on slice(). The function you are referring to is splice() with a 'p'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.