0

This is probably a very basic question - see a simple code:

var ar1=[];
var ar2=[];
ar1[0] = 'Constant';
ar1[1] = data.attr.const;
ar2.push(ar1);  //OK, ar2 contains one array of two correct elements

ar1[0] = 'R-squared';
ar1[1] = data.attr.rsq;
ar2.push(ar1);   // Not OK - ar2 contains 2 identical arrays

ar1[0] = 'R-sq. adjusted';
ar1[1] = data.attr.rsqadj;
ar2.push(ar1);   // Not OK - ar2 contains 3 identical arrays

The problem is that every time when it executes ar2.push(ar1), it overwrites all elements of ar2. After this code is executed, I get an obect with containing 3 identical arrays. How can I fix it?

Thanks

1
  • Because you are re-using the variable ar1, perhaps? Commented Sep 5, 2013 at 23:49

1 Answer 1

6

Objects in JS are always references (unlike strings or numbers). Whenever you push you're referring to the same object that is already inside the array, you need to clone:

ar2.push(ar1.slice(0)); // clone ar1
Sign up to request clarification or add additional context in comments.

Comments

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.