title: Javascript: Set Data Structure: intersect
body: <p>Trying to get two data sets to intersect but I can't do it.  For example, in my code below, intersecting mySet and mySet2 should yield &quot;1&quot; since they both have a value of &quot;1&quot; in their set.</p>
  <pre><code>var mySet = new Set();
  var mySet2=new Set();
  mySet.add(1);
  mySet.add(2);
  mySet.add(&quot;HELLOOOOO&quot;);
  mySet2.add(&quot;hi&quot;);
  mySet2.add(1);
  
  
  var a = Array(mySet, mySet2);
  console.log(a);
  
  mySet.forEach(function(value) {
      console.log(value);
  });
  
  
  mySet2.forEach(function(value) {
      console.log(value);
  });
  
  function intersection_destructive(a, b)
  {
      var result = new Array();
      while( mySet.length &gt; 0 &amp;&amp; mySet2.length &gt; 0 )
      {
          if      (mySet[0] &lt; mySet2[0] ){ mySet.shift(); }
          else if (mySet[0] &gt; mySet2[0] ){ mySet2.shift(); }
          else /* they're equal */
          {
              result.push(mySet.shift());
              mySet2.shift();
          }
      }
  
      return result;
  }
  </code></pre>
  <p>Set 1 and Set 2 both have &quot;1&quot; in it but my function (intersection_destructive) doesn't return it.  I'm not sure how to intersect them, I searched stackoverflow and found intersection_destructive but it didn't work for me, I also tried:</p>
  <pre><code>array1.filter(function(n) {
      return array2.indexOf(n) != -1
  });
  </code></pre>
  <p>as per this: <a href="https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript">Simplest code for array intersection in javascript</a></p>
  <p>but I get an error on <code>filter</code> when I try to run it.</p>