title: How to get most common values in array: javascript
body: <p>I have to find the most common values in array in JavaScript.</p>
  
  <p>my tried coded </p>
  
  <p>eg arrays </p>
  
  <pre><code>var A = ["a", "c", "a", "b", "d", "e", "f"];
  var B = ["a", "c", "a", "c", "d", "e", "f"];
  
  function mode(array)
  {
      if(array.length == 0)
          return null;
      var modeMap = {};
      var maxEl = array[0], maxCount = 1;
      for(var i = 0; i &lt; array.length; i++)
      {
          var el = array[i];
          if(modeMap[el] == null)
              modeMap[el] = 1;
          else
              modeMap[el]++;  
          if(modeMap[el] &gt; maxCount)
          {
              maxEl = el;
              maxCount = modeMap[el];
          }
      }
      return maxEl;
  }
  </code></pre>
  
  <p>and other one </p>
  
  <pre><code>var store = ['1','2','2','3','4'];
  var frequency = {};  // array of frequency.
  var max = 0;  // holds the max frequency.
  var result;   // holds the max frequency element.
  for(var v in store) {
          frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
          if(frequency[store[v]] &gt; max) { // is this frequency &gt; max so far ?
                  max = frequency[store[v]];  // update max.
                  result = store[v];          // update result.
          }
  }
  </code></pre>
  
  <p>Code works ok in case A, "a" repeat most with 2 times occurrence, so I get "a" that's ok.</p>
  
  <p>but in case of B, "a" &amp; "c" both repeat 2 times but I get only A, but my requirement is to get both  "a" &amp; "c".</p>