简体   繁体   English

JavaScript | 返回字符串中最常见的多个字符

[英]JavaScript | Returning multiple characters that is most common in a string

So I am learning how to return the most common character in a string. 因此,我正在学习如何返回字符串中最常见的字符。 I know how to do it if there is only one character that appears the most-ei, the "a" in "javascript" which appears twice and the rest of the characters appear only once. 我知道如果只有一个字符出现最多ei,“ javascript”中的“ a”出现两次,而其余字符只出现一次,我该怎么做。 But if the string is 'javascript prototype', there are two characters that appear the most which are "p" and "t". 但是,如果字符串是“ javascript原型”,则出现最多的两个字符是“ p”和“ t”。 I am using the _.invert() to get the value of the number in which letters appear the most and I though since "p" and "t" both equal 3 then I could return them. 我正在使用_.invert()来获取字母出现最多的数字的值,但由于“ p”和“ t”都等于3,所以我可以返回它们。 I expected the output to be "pt" 我期望输出为"pt"

 // 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') == 'pt' 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); 

Find the max number in the charMap by spreading the Object.values() into Math.max() . 通过 Object.values() 扩展Math.max() ,在charMap找到最大数量。 Then use Array.filter() to get just the keys that have the max value, and join them with a space: 然后使用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')); // pt 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM