title: Javascript Diagonal Matrix
body: <p>I need to do a simple diagonal matrix in JS, which should look like this  one:</p>
  
  <pre><code>[
    [4, 7, 9],
    [2, 5, 8],
    [1, 3, 6]
  ]
  </code></pre>
  
  <p>My idea is to use a 2-d array and two loops, but the result I get is an empty array.You'll see below what my code looks like, but obviously I have a problem with the values. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function fillMatrix(n) {
    var matrix = [];
    var rows = 0;
    var cols = 0;
    var startCount = 1;
  
    for (var i = (n - 1); i &gt;= 0; i--) {
      rows = i;
      cols = 0;
      matrix[rows] = [];
      while (rows &lt; n &amp;&amp; cols &lt; n) {
  
        matrix[rows++][cols++] = startCount++;
      }
  
  
      for (var j = 0; j &lt; n; j++) {
        rows = j;
        cols = 0;
        matrix[rows] = [];
        while (rows &lt; n &amp;&amp; cols &lt; n) {
          matrix[cols++][cols++] = startCount++;
        }
      }
    }
    return matrix;
  }
  
  n = +prompt();
  console.log(fillMatrix(n));</code></pre>
  </div>
  </div>
  </p>