I am trying to understand the 2D Arrays in Google Apps script and I have been stuck with this unexpected behavior, I want to change just one element within an I and J position but it results to changing many ones.
function tryMe(){
const total = Array(2).fill(Array(5).fill(0));
Logger.log('Initial array : ');
Logger.log(total);
total[0][3] = 50;
Logger.log('Replacing element (0, 3) with 50 : ');
Logger.log(total);
}
Am I doing something wrong?
2
Answers
In your code:
Array(5).fill(0)
creates an array of 5 elements filled with 0.However Array(2).fill() will fill the array with a value, but if the value is an object it will fill each element of the array with the same object. Since an array is an object
total
will consist of 2 elements each being the same array. Sototal[0]
is the same array astotal[1]
and when you changetotal[0][3] = 50;
you are also changingtotal[1][3]
A solution would be:
Reference
In your code, This syntax
Array(2).fill(<object>)
is a culprit. As per thedocumentation
, If value offill()
is an object, each slot in the array will reference that object.Which means updating one object will modify all the object as all are referencing the same address.
To get rid from this, You can use Array.push() instead of Array.fill() for
<object>
values.Live Demo :