【发布时间】:2016-02-11 16:39:04
【问题描述】:
我正在尝试重做这个函数,所以它返回多个值。到目前为止,它只返回第一个,所以如果我有一个带有“Hello to all from Boston”的句子,它只会返回 Hello,我想改写这个函数,它返回 ["Hello", “全部”,“波士顿”]。
顺便说一句,我从之前的thread得到了这个解决方案。
function returnFirstRepeatChar2(str){
return ((str = str.split(' ').map(function(word){
var letters = word.split('').reduce(function(map, letter){
map[letter] = map.hasOwnProperty(letter) ? map[letter] + 1 : 1;
return map;
}, {}); // map of letter to number of occurrence in the word.
return {
word: word,
count: Object.keys(letters).filter(function(letter){
return letters[letter] > 1;
}).length // number of repeated letters
};
}).sort(function(a, b){
return b.count - a.count;
}).shift()) && str.count && str.word) || -1; //return first word with maximum repeated letters or -1
}
console.log(returnFirstRepeatChar2("Hello and hello again"));
这里是bin。顺便说一句,这只是原始线程的解决方案之一,不确定它是否是性能最好的解决方案。
【问题讨论】:
-
您的真正目标是什么?没有真正理解这个问题。
-
@RejithRKrishnan OP 想要打印字符串中包含重复字母的所有单词(hello 有 2 l,all 有 2 l,boston 有 2 o)
-
我很抱歉,也许我的问题没有很好地表达。我想返回一个包含多个字符的单词数组......所以如果给定字符串“Hello all from Boston”,我会得到结果 ["Hello", "all", "Boston"].. . 但是,如果我在该字符串中有一个包含更多相同字符的单词,例如“Whooooa,Hello all from Boston”,我希望我的数组返回具有最多重复字母的单词,例如 ["whooooa"]
标签: javascript arrays