2014-08-28 166 views
0
$.each(string.split(''), function(){ 
    if(!check[this]){ 
     count++; 
     check[this]=true; 
    } 
}) 

对于我上面的函数,它能够计算唯一字符的数量。例如,对于1113,结果将为2,因为那里只有1和3.对于1134,结果将为3,因为有1,3和4.在JavaScript中计算字符串中数字的出现次数

但是我想举个例子1133和1113,有相同的2个唯一编号是1和3.我如何计算1和3的最大值?对于1133这将是2,而对于1113它将是3,因为1出现3次。

我只需要计算字符串中出现最多的数字(仅限数字)的出现次数。

回答

0

存储计数并找出计数的最大值。这是投入的函数代码:

function getMostOccurrence(str) { 
    var check = {}; 
    var maxOccurrences = 0; 

    // This part you already have...kind of 
    str.split('').forEach(function(num) { 
     // Set it the first time 
     if (typeof check[num] === 'undefined') { 
      check[num] = 0; 
     } 

     // Increase it 
     check[num] += 1; 
    }); 

    // Find the max of that 
    for (var num in check) { 
     if (check.hasOwnProperty(num)) { 
      if (check[num] > maxOccurrences) { 
       maxOccurrences = check[num]; 
      } 
     } 
    } 

    return maxOccurrences; 
} 
1

你需要几个帮手:

// Given an object, it returns the values in an array 
// {a:1, b:2} => [1,2] 
var values = function(x) { 
    return Object.keys(x).map(function(k){return x[k]}) 
} 

// Given an array, it counts occurrences 
// by using an object lookup. 
// It will return an object where each key is an array item 
// and each value is the number of occurrences 
// [1,1,1,3] => {'1':3, '3':1} 
var occurrences = function(xs) { 
    return xs.reduce(function(acc, x) { 
    // If key exists, then increment, otherwise initialize to 1 
    acc[x] = ++acc[x] || 1 
    return acc 
    },{}) 
} 

// Composing both helpers 
var maxNumberOccurrence = function(n) { 
    // To get the maximum value of occurrences 
    // we use Math.max with `apply` to call the function 
    // with an array of arguments 
    return Math.max.apply(0, values(occurrences(n.toString().split('')))) 
} 

maxNumberOccurrence(1113) //=> 3 
+0

你的方法看起来更复杂。您是否介意评论/解释它,以便我们都可以了解这里发生的情况而无需手动解码? – 2014-08-28 07:56:38

+0

检查编辑,我添加了一些评论。 – elclanrs 2014-08-28 08:01:52

+0

非常好。虽然我想知道是否有任何理由使用'Array.prototype.reduce'作为迭代器? – 2014-08-28 08:06:13

相关问题