你需要幾個幫手:
// 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