0

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)
}
1
  • 1
    Which programming language are you using? Commented May 23 at 21:49

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Carcigenicate ! I get it now, I was thinking the array would keep a snapshot of the values of pair. Makes sense that it is a reference to the pair object.

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.