title: Finding intersection of arrays not working?
body: <p>I have a two dimensional array with an arbitrary number of elements in each dimension, so it's an [m][n] array, but the second dimension length (<code>n</code>) is variable. </p>
  
  <p>Each element in the second dimension contains a number and there will only be one number that exists in all of the dimensions. </p>
  
  <p>So, for example, the array might be:</p>
  
  <pre><code>[
      [
          126, 
          131, 
          138, 
          139, 
          140, 
          143
      ],
      [
          126,
          201
      ]
  ]
  </code></pre>
  
  <p>Keep in mind that <code>m</code> can be > 2.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>var theArray = [
    [126, 131, 138, 139, 140, 143],
    [126, 201]
  ];
  
  for(var i = 0; i &lt; theArray.length; i++) // loop through each array of numbers
  {
      $.each(theArray[i], function(index, value) // loop through all of the numbers in this array
      {
          var nextArray = (i+1&lt;theArray.length?theArray[i+1]:theArray[0]);
          if($.inArray(value, nextArray) == -1) // if this number is not in the next array
          {
              console.log("removing index: " + index + ", value: " + value);
              theArray[i].splice(index, 1); // remove the number from the array
          }
      });
  }
  console.log(theArray);
  </code></pre>
  
  <p>The output is this:</p>
  
  <pre><code>removing index: 1, value: 131
  removing index: 2, value: 139
  removing index: 3, value: 143
  removing index: 4, value: undefined
  removing index: 5, value: undefined
  removing index: 1, value: 201
  
  Array
      [
          [
              126, 
              138, 
              140, 
          ],
          [
              126
          ]
      ]
  </code></pre>
  
  <p>JSFIDDLE: <a href="http://jsfiddle.net/hDL8K/" rel="nofollow">http://jsfiddle.net/hDL8K/</a></p>
  
  <p>As you can see, it <em>almost</em> works, but it fails to remove two of the values.</p>
  
  <p>I think this might have something to do with the <code>index</code> in the <code>foreach</code> loop increasing with each loop and the array size decreasing because elements are being removed, but I'm not sure.</p>
  
  <p>Why is this not working, and how can I fix it?</p>