title: Javascript - nested loops and indexes
body: <p>I am trying to build an array that should look like this :</p>
  
  <pre><code>[
   [{"name":"Mercury","index":0}],
   [{"name":"Mercury","index":1},{"name":"Venus","index":1}],
   [{"name":"Mercury","index":2},{"name":"Venus","index":2},{"name":"Earth","index":2}],
  ...
  ]
  </code></pre>
  
  <p>Each element is the concatenation of the previous and a new object, and all the indexes get updated to the latest value (e.g. Mercury's index is 0, then 1, etc.). 
  I have tried to build this array using the following code :</p>
  
  <pre><code>var b = [];
  var buffer = [];
  var names = ["Mercury","Venus","Earth"]
  for (k=0;k&lt;3;k++){
  
      // This array is necessary because with real data there are multiple elements for each k
      var a = [{"name":names[k],"index":0}]; 
  
      buffer = buffer.concat(a);
  
      // This is where the index of all the elements currently in the 
      // buffer (should) get(s) updated to the current k 
      for (n=0;n&lt;buffer.length;n++){
          buffer[n].index = k;
      }
  
      // Add the buffer to the final array
      b.push(buffer);
  
  }
  console.log(b);
  </code></pre>
  
  <p>The final array (b) printed out to the console has the right number of objects in each element, but all the indexes everywhere are equal to the last value of k (2). 
  I don't understand why this is happening, and don't know how to fix it.</p>