Best way in JavaScript to "intersect" two arrays of JSON objects by common property?
<p>Let's say we have two arrays, <code>arr1</code> and <code>arr2</code>, of JSON objects that share a common property <code>id</code>: </p>

<pre><code>var arr1 = [{'id':10,'value1':'a1'},
            {'id':11,'value1':'b1'},
            {'id':12,'value1':'c1'},
            {'id':13,'value1':'d1'},
            {'id':14,'value1':'e1'}];

var arr2 = [{'id':100000,'value2':'a2'},
            {'id':11,'value2':'b2'},
            {'id':100002,'value2':'c2'},
            {'id':100003,'value2':'d2'},
            {'id':14,'value2':'e2'}];
</code></pre>

<p>I need to extract the "value" items from both arrays where the IDs match, i.e. the expected output would be:</p>

<pre><code>[0] value1: b1, value2: b2
[1] value1: e1, value2: e2
</code></pre>

<p>I have a working sample of a nested-loop solution (see below), but it's slow (imagine these arrays being large and some UI operations involved for each iteration), so I really hope there is a more elegant and quicker solution for this.</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr1 = [{'id':10,'value1':'a1'},
            {'id':11,'value1':'b1'},
            {'id':12,'value1':'c1'},
            {'id':13,'value1':'d1'},
            {'id':14,'value1':'e1'}];

var arr2 = [{'id':100000,'value2':'a2'},
            {'id':11,'value2':'b2'},
            {'id':100002,'value2':'c2'},
            {'id':100003,'value2':'d2'},
            {'id':14,'value2':'e2'}];

for (var i = 0, len1 = arr1.length; i &lt; len1; i++) {
 for (var j = 0, len2 = arr2.length; j &lt; len2; j++) {
  if (arr1[i].id === arr2[j].id) {
   theFunction(arr1[i].value1, arr2[j].value2);
   break;
  }
 }
}

function theFunction(value1, value2) {
  var div = document.getElementById('out');
  div.innerHTML += '&lt;br /&gt;value1: ' + value1 + ', value2: ' + value2;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id='out'&gt;
&lt;/div&gt;</code></pre>
</div>
</div>
</p>