javascript - JavaScript 中计算字符串中数字出现的次数

标签 javascript jquery

$.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/

相关文章:

javascript - 如何在 Angular 4中的依赖注入(inject)之前从服务器加载路由配置?

javascript - 我正在尝试创建一个带有框架的 JSP 页面

javascript - 使用jquery插入 anchor 来调用函数

javascript - 如何在不重新加载页面的情况下更改目标窗口的 location.hash?

java - 如何在servlet中使用ajax请求中传递的json对象

JavaScript生成的Materialise卡片显示问题

javascript - 成功的 ajax 调用后更新 bootstrap popover 的内容

javascript - 文本输入只需要一位或多个相同的数字

javascript - 设置全局 ajax 数据类型会破坏 rails 远程链接

javascript - 更改分页中选定的页面