$.each(string.split(''), function(){
if(!check[this]){
count++;
check[this]=true;
}
})
对于上面的函数,它能够计算唯一字符的数量。例如,对于 1113
,结果将为 2,因为只有 1 和 3。对于 1134
,结果将为 3,因为只有 1,3 和 4。
但是我想例如1133和1113,有相同的2个唯一数字,即1和3。如何计算1和3的最大出现次数?对于 1133
来说,它是 2,而对于 1113
来说,它是 3,因为 1
出现了 3 次。
我只需要计算字符串中出现次数最多的数字的出现次数(仅数字)。
最佳答案
你需要几个 helper :
// 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
关于javascript - JavaScript 中计算字符串中数字出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25543370/