title: Simple histogram algorithm in Javascript
body: <p>Im creating a histogram algorithm. Im following the solution offered <a href="https://stackoverflow.com/a/4515959/1246159">here</a>.</p>
  
  <p>I want to simply count the number of times each value has occurred.</p>
  
  <p>However I cant quite get the algorithm right. My code is:</p>
  
  <pre><code>var values = [2, 4, 6, 3, 3];
  
  var val_max = 6;
  var val_min = 2;
  
  var num_bins = parseInt(val_max - val_min + 1);
  console.log('num_bins is ', num_bins);
  
  var bin_width = (val_max-val_min)/num_bins;
  console.log('bin_width is ', bin_width);
  
  var to_plot = [];
  
  for (var i = 0; i &lt; num_bins; i++) {
    to_plot.push(0);
  }
  
  for (var x = 0; x &lt; values.length; x++) {
  
      var bin_idx = parseInt((values[x] - val_min) / bin_width); 
  
      to_plot[bin_idx] = to_plot[bin_idx] + 1; 
  }
  
  console.log('to_plot is ', to_plot);
  </code></pre>
  
  <p>If you look at the console logs, you'll see:</p>
  
  <pre><code>to_plot is  [1, 2, 1, 0, 0, NaN]
  </code></pre>
  
  <p>I want that last index to be "1". But the problem is for values close the the maximum value, <code>bin_idx</code> is out of range. How can I tweak this so that I would get the following results?</p>
  
  <pre><code>to_plot is  [1, 2, 1, 0, 1] 
  </code></pre>
  
  <p>The jsfiddle is <a href="https://jsfiddle.net/6ka74jmg/1/" rel="nofollow noreferrer">here</a>. </p>