你需要几个帮手:
// 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
你的方法看起来更复杂。您是否介意评论/解释它,以便我们都可以了解这里发生的情况而无需手动解码? – 2014-08-28 07:56:38
检查编辑,我添加了一些评论。 – elclanrs 2014-08-28 08:01:52
非常好。虽然我想知道是否有任何理由使用'Array.prototype.reduce'作为迭代器? – 2014-08-28 08:06:13