Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Im parsing a json object and storing the values I want in an array, I then push each array into a second array inside the for loop to create an array where each element in a2 is a1.

Im already getting and parsing the json correctly.

var a1 = [];
var a2 = [];

for(i = 0; i < json.results.query.length; i++) {
   var date = json.results.query[i].Date;
   var name = json.results.query[i].Name;

   a1[0] = date;
   a1[1] = name;

   console.log(a1);
   a2.push(a1);
}

console.log(a2);

console.log(a1) prints the correct array, which changes for each iteration of the for loop. For example:

["2014-01-01", "John"]
["2014-01-02", "Ann"]
["2014-01-03", "Mike"]

But console.log(a2) prints the a2 array with the last a1 values for every index:

[["2014-01-03", "Mike"],
["2014-01-03", "Mike"],
["2014-01-03", "Mike"]]

I also tried assigning a1 to each index of a2 inside the for loop instead of using .push() such as:

a2[i] = a1;

I want the nested (or 2-d) array, but why is each element the same?

What is going on here? Is there some javascript scoping rule? This works in other languages. Thanks!

share|improve this question

3 Answers 3

up vote 2 down vote accepted

Each time you go around the loop you modify the existing array referenced by a1 and then push a reference to it into the array referenced by a2.

This means you end up with multiple references to the same array.

You need to create a new array to push for each set of data.

Move var a1 = []; inside the loop.

share|improve this answer

I think you need a2.push(a1); not a2.push(a2); (in for-loop)

Or try this:

for(i = 0; i < json.results.query.length; i++) {
   var date = json.results.query[i].Date;
   var name = json.results.query[i].Name;

   a2.push([date, name]);
}

Note: In first way, you should declare a1 inside the for-loop NOT outside at top of it.

share|improve this answer
    
That was a typo. Sorry. I have a2.push(a1) –  brno792 19 mins ago
    
@brno792 Please see my note at end of my answer –  ABFORCE 18 mins ago

a1 is a reference of your array object, and your for loop is keeping changing the object value.

you need to copy a1 value to some variable first then push the variable to a2.

try:

var a1 = [];
var a2 = [];
function pushToA2(a){
 a2.push(a);
} 

for(i = 0; i < json.results.query.length; i++) {
  var date = json.results.query[i].Date;
  var name = json.results.query[i].Name;

  a1[0] = date;
  a1[1] = name;

  pushToA2(a1);

}

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.