arrayspush

Pushing new values to an array is writing over the values of previous elements


I am trying to push multiple data sets(arrays) to my array called colors. As I continue to push new data it seems to overwrite the values in previous elements of the colors array. I have included a simple example showing that push#3 overwrites the values in the 2nd element of the colors array. I do not understand why that is happening.

I am expecting the colors array to contain 3 elements [[R, Red],[B, Blue],[G, Green]] but what I get is [[G, Green],[G, Green],[G,Green]]

function myFunction() {
  var colors = []
  var pair = []

  //===============================
  pair[0]= 'R'
  pair[1]= 'Red'
  // push 1
  colors.push(pair)

  Logger.log('pair=')
  Logger.log(pair)
  Logger.log('colors= ')
  Logger.log(colors)

  //================================
  pair[0] = 'B'
  pair[1] = 'Blue'
  // push #2
  colors.push(pair)

  Logger.log('\n\n')
  Logger.log('pair=')
  Logger.log(pair)
  Logger.log('colors= ')
  Logger.log(colors)

  //================================
  pair[0] = 'G'
  pair[1] = 'Green'
  // push #3
  
  colors.push(pair)
  Logger.log('\n\n')
  Logger.log('pair=')
  Logger.log(pair)
  Logger.log('colors= ')
  Logger.log(colors)
}

Solution

  • You keep pushing the same pair over and over. Javascript won't make a copy of pair just because you added it to an array. So, if you do pair[0] = 'G', that affects all the references to pair that are already in the array, because they're all referencing the same object.

    Just create a new object each time:

    colors.push(['R', 'Red']);
    colors.push(['B', 'Blue']);
    colors.push(['G', 'Green']);
    

    Note how I'm using the literal syntax ([]) each time, which in this context creates a new array each time. You could have also done something like:

    let pair = ['R', 'Red']
    colors.push(pair);
    
    pair = ['B', 'Blue']
    colors.push(pair);
    
    pair = ['G', 'Green']
    colors.push(pair);
    

    In this case, the variable is reused, but is reassigned a new object for each color channel.