title: How do I dynamically create circular referencing objects in Javascript?
body: <p>I'm trying to implement <a href="https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X" rel="nofollow noreferrer">DLX</a> in Javascript and I'm running into problems with building circular references. </p>
  
  <p>This function takes a binary matrix and returns a matrix where every '1' of the matrix is an object referencing it's closed '1' in all cardinal directions.</p>
  
  <pre><code>export const constructDataObjects = matrix =&gt; {
    for (let i = 0; i &lt; matrix.length; i++) {
      for (let j = 0; j &lt; matrix.length; j++) {
        let u = j - 1;
        let d = j + 1;
        let l = i - 1;
        let r = i + 1;
  
        if (matrix[i][j] === 0) continue;
  
        // Check edge cases.
        if (u &lt; 0) u = matrix.length - 1;
        if (d &gt;= matrix.length) d = 0;
        if (l &lt; 0) l = matrix.length - 1;
        if (r &gt;= matrix.length) r = 0;
  
        // Increment and decrement directions and bound check.
        // On hitting a bound, circle around and start from the other side.
        while (matrix[i][u] === 0) u = u - 1 &lt; 0 ? matrix.length - 1 : u - 1;
        while (matrix[i][d] === 0) d = d + 1 &gt;= matrix.length ? 0 : d + 1;
        while (matrix[l][j] === 0) l = l - 1 &lt; 0 ? matrix.length - 1 : l - 1;
        while (matrix[r][j] === 0) r = r + 1 &gt;= matrix.length ? 0 : r + 1;
        matrix[i][j] = {
          u: matrix[i][u],
          d: matrix[i][d],
          l: matrix[l][j],
          r: matrix[r][j],
        };
      }
    }
  
    return matrix;
  };
  </code></pre>
  
  <p>I believe this problem can be reduced to:</p>
  
  <pre><code>let a = arr =&gt; {
    for(let i = 0; i &lt; arr.length; i++) {
      n[i] = {
        curr: arr[i],
        first: arr[0],
      }
    }
    return arr
  }
  </code></pre>
  
  <p>now</p>
  
  <pre><code>a([1,2])
  </code></pre>
  
  <p>Produces</p>
  
  <pre><code>[ { curr: 1, first: 1 },
    { curr: 2, first: { curr: 1, first: 1 } } ]
  </code></pre>
  
  <p>What I want is </p>
  
  <pre><code>[ { curr: 1, first: { curr: 1, first: 1 } } },
    { curr: 2, first: { curr: 1, first: 1 } } ]
  </code></pre>
  
  <p>How can I assign <code>first: arr[0]</code> to the <strong>reference</strong> of the <code>a[0]</code> object instead of <code>a[0]</code>'s value at the time of assignment? </p>
  
  <p>I realize </p>
  
  <pre><code>n[i] = {
    curr: arr[i],
    first: arr[0],
  }
  n[i].first = n[0]
  </code></pre>
  
  <p>would work, but I don't see that working in <code>constructDataObjects</code> because the relationships are not known until all elements have been traversed.</p>