如何使用JavaScript查找出现次数最多的数字?

时间:2012-04-08 08:51:15

标签: javascript count find-occurrences

如果用户输入5个号码,请说... 4, 4, 7, 7, 4。 4次发生3次(最多次)次数。所以输出应该是4

如何使用JavaScript执行此操作?非常感谢你的帮助。 谢谢!

到目前为止我已经尝试过了。它有效,但它太长了,寻找简短的方法。

P.S。这不是我的功课!

    var n = parseInt(prompt("How many numbers do you like to enter?", ""));
    var num = new Array();

    for (i = 1; i <= n; i++) {
        num[i] = parseInt(prompt("Enter a number", ""));
        document.write("Entered numbers are: " + num[i] + "<br/>");
    }

    var total = new Array();
    for (i = 1; i <= n; i++) {
        var count = 1;
        for (j = i + 1; j <= n; j++) {
            if (num[i] == num[j]) {
                count++;
            }
            total[i] = count;
        }
    }

    var most = 0;
    for (i = 0; i < n; i++) {
        if (most < total[i]) {
            most = total[i];
        }
        var val = i;
    }
    document.write("<br/>" + num[val] + " is occurred " + most + " times");

5 个答案:

答案 0 :(得分:4)

使用array创建包含大量数字的array literals a

var a = [1, 2, 3, 4, 4, 5, 1, 2, 3, 1, 2, 1, 1];

使用object literals创建普通对象o

var o = {},          /* Creates a new object */
    i = 0,           /* Declare variable i, initialise value at 0*/
    m = {m:0,t:null},
    t,               /* Declare variable t */
    len = a.length;  /* Declare variable len, set value to the array's length */

使用for(;;)-loop循环遍历数组a并递增计数器。计数器存储在对象o的哈希映射中 第一次出现密钥时需要(o[a[i]] || 0):如果找不到,则使用值0代替undefined。另请参阅Short-circuit evaluation: Logical OR

for ( ; i < len ; i++ ) {
    o[ a[i] ] = ( o[ a[i] ] || 0 ) + 1;
}

然后你有一个对象o,它看起来像:

o = {
    "1": 5,
    "2": 3,
    "3": 2,
    "4": 2,
    "5": 1
}

然后使用for(.. in ..)-loop循环浏览o,找到最多显示的时间 在循环的底部,使用conditional ternary .. ? .. : ..运算符:

for ( i in o ) {
    t = { 
        m: o[i], 
        i: i 
    };
    m = m.m < t.m ? t : m;
}

此循环后m等于:

m = { 
    i: "1", 
    m: "5"
};

可以使用以下方法捕获最大值:

o[m];
女巫给你:

5

样本

http://jsbin.com/utiqey/

var a = [1, 2, 3, 4, 4, 5, 1, 2, 3, 1, 2, 1, 1]; 

var o = {}, 
    i = 0, 
    m = {m:0,t:null}, 
    t,
    len = a.length; 

for ( ; i < len ; i++ ) { 
    o[ a[i] ] = ( o[ a[i] ] || 0 ) + 1; 
} 


for ( i in o ) { 
    t = { 
        m: o[i], 
        i: i 
    };
    m = m.m < t.m ? t : m;
} 

alert(m.i + " is the highest presented " + m.m + " times"); 

答案 1 :(得分:3)

无需进行两次通过,以下累计最大值:

var g = [4, 4, 7, 7, 4, 5, 6, 7, 8, 6, 5, 2, 2, 2, 3, 4, 5]; //your array

for (var t = {}, maxn = g[0], max = 0, gi, i = g.length; i--;) {
  if (max < (t[gi = g[i]] = (t[gi] || 0) + 1)) {
    max = t[gi];
    maxn = gi;
  }
}

document.write ('The number ' + maxn + ' occurs ' + max + 'times');

修改

一个很好的解决方案,但OP可能需要一些解释和一些更合适的变量名称。集合中最常出现的值是模式

// Use any member of g to seed the mode
var mode = g[0];
// The number of times the current mode has occurred
var count = 0;
// Results object
var t = {};
var i = g.length;
var gi;

// Loop over all the members
while (i--) {

  // Get the value at i
  gi = g[i];

  // Keep track of how many times the value has been found  
  // If the number hasn't occured before, add it with count 1
  // Otherwise, add 1 to its count
  t[gi] = (t[gi] || 0) + 1;

  // Set the mode to the current value if it has occurred 
  // more often than the current mode
  if (count < t[gi]) {
    count = t[gi];
    mode = gi;
  }
}

alert('The mode is ' + mode + ' and occurs ' + count + ' times.');

如果有多个模式,那么首先从数组末尾找到 count 次的模式获胜。

答案 2 :(得分:2)

http://jsbin.com/ageyol/3/edit

var g = [4, 4, 7, 7, 4, 5, 6, 7, 8, 6, 5, 2, 2, 2, 3, 4, 5]; //your array
var t = {}; // object which contain the numbers as properties.

for (var i = 0; i < g.length; i++)
{
    if (!t[g[i]]) t[g[i]] = 0; //if the property doesnt exists , so create one with counter 0.
    t[g[i]]++; // also - increase the property VALUE.
}

var max = 0;

for (i in t)
{
    if (t[i] > max) max = t[i]; //check if property value is larger then the current MAX val.
    document.write(i + "  " + t[i] + "<br/>");
}
document.write(t[max]);

P.S。如果超过最大值 - 那么你应该迭代。

答案 3 :(得分:2)

对数组进行排序,然后相同的值彼此相邻,这样你就可以循环遍历它们并寻找最长的条纹:

arr.sort();

var maxValue, maxCount = 0, cnt = 1, last = arr[0];
for (var i = 1; i <= arr.length; i++) {
  if (i = arr.length || arr[i] != last) {
    if (cnt > maxCount) {
      maxCount = cnt;
      maxValue = last;
    }
    cnt = 1;
    if (i < arr.length) last = arr[i];
  } else {
    cnt++;
  }
}

答案 4 :(得分:0)

只需重复其他一个答案,一旦你形成了你的值对象,就可以将值推送到数组中并使用Math.max来获得上限。通常Math.max需要一系列数字,但如果您使用.apply,它也可以接受arrayMath.min也是如此。

var o = { 1: 5, 2: 3, 3: 2, 4: 2, 5: 1 };

var out = [];
for (var k in o) {
  out.push(o[k]);
}

var upperbound = Math.max.apply(null, out); // 5