skip to Main Content

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);
}

The result I get :
enter image description here

Am I doing something wrong?

2

Answers


  1. In your code:

    const total = Array(2).fill(Array(5).fill(0));
    

    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. So total[0] is the same array as total[1] and when you change total[0][3] = 50; you are also changing total[1][3]

    A solution would be:

    const total = new Array(2);
    total = total.map( row => new Array(5).fill(0) );
    

    Reference

    Login or Signup to reply.
  2. In your code, This syntax Array(2).fill(<object>) is a culprit. As per the documentation, If value of fill() 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 :

    const total = [];
    
    const parentArrayElements = 2;
    
    for (let i = 1; i <= parentArrayElements; i++) {
      total.push(Array(5).fill(0))
    }
    
    console.log('Initial array : ');
    console.log(total); // [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
    total[0][3] = 50;
    console.log('Replacing element (0, 3) with 50 : ');
    console.log(total); // [[0, 0, 0, 50, 0], [0, 0, 0, 0, 0]]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search