Javascript get table cell 2D array considering colspan and rowspan
<p>I have a table with colspans and rowspans like this 5x3 table:</p>

<pre><code>&lt;table id="test"&gt;
  &lt;tr&gt;
    &lt;td colspan="2"&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;td rowspan="2"&gt;3&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;5&lt;/td&gt;&lt;td colspan="2"&gt;6&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;8&lt;/td&gt;&lt;td&gt;9&lt;/td&gt;&lt;td&gt;10&lt;/td&gt;&lt;td&gt;11&lt;/td&gt;&lt;td&gt;12&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
</code></pre>

<p><a href="https://i.stack.imgur.com/w3mIg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w3mIg.png" alt="example"></a></p>

<p>I want to create 2D array in Javascript which contains cell DOM elements at given coordinates.<br>
For given example it is following (for simplicity, numbers mean DOM cell elements with corresponding content):</p>

<pre><code>[[1, 1, 2, 3, 4], [5, 6, 6, 3, 7], [8, 9, 10, 11, 12]]
</code></pre>

<p>You see, it is like Javascript property <code>table.rows</code>, but cells with colspan/rowspan appear many times. 
If only colspan is allowed it is not difficult to create such array - just loop over <code>table.rows</code> and push to array cells as many times as colspan is. However, when rowspan is also allowed, this becomes tricky.</p>

<p>Here is my attempt:</p>

<pre><code>  var tableEl = document.getElementById('test');
  var cells2D = [];
  var rows = tableEl.rows;
  var x = 0, y = 0;
  for (var r = 0; r &lt; rows.length; ++r) {
    var cells = rows[r].cells;
    x = 0;
    for (var c = 0; c &lt; cells.length; ++c) {
      var cell = cells[c];
      var colSpan = x + (cell.colSpan || 1);
      var rowSpan = y + (cell.rowSpan || 1);
      for (var x2 = x; x2 &lt; colSpan; ++x2) {
        for (var y2 = y; y2 &lt; rowSpan; ++y2) {
          if (!cells2D[y2]) cells2D[y2] = [];
          cells2D[y2][x2] = cell;
        }
        ++x;
      }
    }
    ++y;
  }
</code></pre>

<p>It doesn't works on example, but if I remove last column then it works.</p>