title: JavaScript: Get unique values and their counts from an array of objects?
body: <p>Using jQuery, how can I iterate over an object, and get the unique values of a key with a count of each value?</p>
  
  <p>For example, for this array:</p>
  
  <pre><code>var electrons = [
      { name: 'Electron1', distance: 1 }, 
      { name: 'Electron2', distance: 1 }, 
      { name: 'Electron3', distance: 2 }, 
      { name: 'Electron4', distance: 2 }, 
      { name: 'Electron5', distance: 2 }, 
      { name: 'Electron6', distance: 2 }, 
      { name: 'Electron7', distance: 2 }, 
      { name: 'Electron8', distance: 2 }, 
      { name: 'Electron9', distance: 2 }, 
      { name: 'Electron10', distance: 2 }, 
      { name: 'Electron11', distance: 3 }, 
  ];
  </code></pre>
  
  <p>I'd like to get back the following:</p>
  
  <pre><code>var distance_counts = {1: 2, 2: 8, 3: 1};
  </code></pre>
  
  <p>I've got this, which works but is a bit clumsy:</p>
  
  <pre><code>var radius_counts = {};
  for (var i = 0; i &lt; electrons.length; i++) { 
      if (electrons[i].distance in radius_counts) { 
           radius_counts[electrons[i].distance] += 1;
      } else { 
           radius_counts[electrons[i].distance] = 1;
      } 
  }
  </code></pre>