Argyll
Argyll

Reputation: 9875

How to create a true new copy of an array in App Script for Google Sheet?

I am having the following problem with App Script in Google Sheet.

I want to make different copies of a row in my sheet base on a table. I want to do something like

input1=[[1,2,"a"]];
input2=[[4,5,"b"],[7,8,"c"]];
function (input1,input2) {
   \\ input# is a row, ie. an array with single element, which is another array
   \\ The rows input# represent are of equal length

   out=[];
   copy1=input1[0];//copy1 is a reference to input1[0]
   copy2=input1[0];//copy2 is a reference to input1[0]
   for (i=0;i<input1.length,i++) {//input1.length is 1
       copy1[i]+=input2[0][i];
       copy2[i]+=input2[1][i];
   }
   out.push(copy1,copy2);//copy1=[5,2,a] copy2=[8,2,a]
   return out
}

I would expect out to look like

out=[[5,7,"ab"],[8,10,"ac"]];//[[5,2,a],[8,2,a]]

But it doesn't. The output looks like whenever I modified copy1 or copy2, it was input1 itself that was modified.

What is wrong here? How can I create a new array variable, assign its value as equal to an existing array and modify the new array without changing the old? Is it ok to have input arrays that whose elements (of elements) consist of mixed numeric and strings?

Upvotes: 5

Views: 6736

Answers (2)

Biz Bot9
Biz Bot9

Reputation: 7

 //-- Append our new needs to needs without changing needs
 var needs = ["FunctionName", "Source", "User"]
 var newNeeds = needs.slice(0,needs.length) // Creates a new Exact copy duplicate of an array
 newNeeds.push("Code") 
 Logger.log(needs) // Expect ["FunctionName", "Source", "User"] No Change
 Logger.log(newNeeds) // Expect ["FunctionName", "Source", "User","Code"] Added "Code"
 debugger

Upvotes: -1

Cooper
Cooper

Reputation: 64110

Using Slice() to return a copy of an Array

Try it this way:

function myFunction(input1,input2) 
{
   var input1=[[1,2,"a"]];
   var input2=[[4,5,"b"],[7,8,"c"]];
   var out=[];
   var copy1=input1[0].slice();//slice returns a copy of the array
   var copy2=input1[0].slice();
   for (var i=0;i<input1[0].length;i++)//looping through all of elements of input1[0]; 
   {
       copy1[i]+=input2[0][i];
       copy2[i]+=input2[1][i];
   }
   out.push(copy1,copy2);
   Logger.log(out);//out=[[5,7,"ab"],[8,10,"ac"]];
}

For more information on slice look here.

This is a good question. I've struggled with it a few times myself.

Upvotes: 6

Related Questions