Javascript Array mode()

Description

Javascript Array mode()


Array.prototype.mode = function() {
    var array_length, count, i, max, value;
    array_length = this.length;
    count = [];/*from w w w .ja  v  a  2 s  .  c  om*/
    for (i = 0; i < array_length; i++) {
        if (count[this[i]]) {
            count[this[i]] ++;
        } else {
            count[this[i]] = 1;
        }
    }
    max = 0;
    for (i = 0; i < count.length; i++) {
        if (count[i] > max) {
            max = count[i];
            value = i;
        }
    }
    if (value > 1) {
        return value;
    } else {
        return null;
    }
};

Javascript Array mode()

Array.prototype.mode = function(){
  if(this.length == 0)
    return null;/*  www .  java 2s.  co  m*/
  var modeMap = {};
  var maxEl = this[0], maxCount = 1;
  for(var i = 0; i < this.length; i++)
  {
    var el = this[i];
    if(modeMap[el] == null)
      modeMap[el] = 1;
    else
      modeMap[el]++;
    if(modeMap[el] > maxCount)
    {
      maxEl = el;
      maxCount = modeMap[el];
    }
  }
  return maxEl;
}



PreviousNext

Related