因此,我正在学习如何返回字符串中最常见的字符。如果只有一个字符出现最多,我知道该怎么做。例如,“ javascript”中的“ a”出现两次,其余字符仅出现一次。但是,如果字符串是“ javascript原型”,则出现最多的两个字符是“ p”和“ t”。我正在使用_.invert()来获取字母出现最多的数字的值,但是由于“ p”和“ t”都等于3,所以我可以返回它们。我期望输出是
"p t"
// Return the character that is most common in a string
// ex. maxCharacter('javascript') == 'a'
// Return multiple characters that are most common in a string
// ex. maxCharacter('javascript prototype') == 'p t'
function maxCharacter(str) {
const charMap = {};
let maxNum = 0;
let maxChar = '';
str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});
for(let char in charMap){
if(charMap[char] > maxNum) {
maxNum = charMap[char];
maxChar = (_.invert(charMap))[maxNum];
}
}
return maxChar;
}
// Call Function
const output = maxCharacter('javascript prototype');
console.log(output);
最佳答案
在charMap
中通过spreading将Object.values()
放入Math.max()
中找到最大数目。然后使用Array.filter()
仅获取具有最大值的键,并用空格将它们连接起来:
function maxCharacter(str) {
const charMap = {};
str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});
const max = Math.max(...Object.values(charMap));
return Object.keys(charMap)
.filter((c) => charMap[c] === max)
.join(' ');
}
console.log(maxCharacter('javascript')); // a
console.log(maxCharacter('javascript prototype')); // p t
关于javascript - JavaScript |返回字符串中最常见的多个字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50106031/