简体   繁体   English

Javascript获取字符串中所有最常用的字符

[英]Javascript get all the most frequent characters in a string

I need help on how can I get not just one but other most common character/letter in a string.我需要帮助,我如何能得到只是一个,但在一个字符串最常见的字符/字母。

my code only works on getting one of the common character.我的代码仅适用于获取常见字符之一。

but when more than one character are equally common only one are returned.但是当多个字符同样常见时,只返回一个。 I would like it to return two character if two character are common.如果两个字符很常见,我希望它返回两个字符。

const x = mostCommonCharacter("abbbcddefffg");
console.log(x); // result is *b* 

if b and f are most common I would like to return bf如果bf是最常见的,我想返回bf

  function mostCommonCharacter(str) {
  const charHolder = {}; // { a: 1, b: 3, c: 1, d: 2, e: 1, f: 3, g: 1 }

  str
    .toLowerCase()
    .split("")
    .forEach(char => {
      if (char != " ") {
        if (charHolder[char] == null) {
          charHolder[char] = 1;
        } else {
          charHolder[char] += 1;
        }
      }
    });
  let highest_num = 0;
  let letter = "";
  for (const key in charHolder) {
    if (charHolder[key] > highest_num) {
      highest_num = charHolder[key];
      letter = key;
    }
  }
  return letter;
}

but It only return one most common character which is " b "但它只返回一个最常见的字符“ b

what I need is for it to return " b " and " f " because both of them are most common.我需要的是它返回“ b ”和“ f ”,因为它们都是最常见的。 and not just b is there a way to do this?而不仅仅是b有没有办法做到这一点?

Get the highest_num and then again iterate through object and get those letters for which count is equal to highest_num获取highest_num ,然后再次遍历对象并获取count等于highest_num那些字母

 function mostCommonCharacter(str) { const charHolder = {}; // { a: 1, b: 3, c: 1, d: 2, e: 1, f: 3, g: 1 } str .toLowerCase() .split("") .forEach(char => { if (char != " ") { if (charHolder[char] == null) { charHolder[char] = 1; } else { charHolder[char] += 1; } } }); let highest_num = 0; for (const key in charHolder) { if (charHolder[key] > highest_num) { highest_num = charHolder[key]; } } let res = ''; for(let k in charHolder){ if(charHolder[k] === highest_num){ res += k; } } return res; } console.log(mostCommonCharacter("abbbcddefffg"))

A shorter version of the code can be obtained by using reduce() and Math.max可以通过使用reduce()Math.max获得更短的代码版本

 function mostCommonCharacter(str) { const charHolder = str .toLowerCase() .split('') .reduce((ac,a) => (ac[a] = ac[a] + 1 || 1, ac), {}); let max = Math.max(...Object.values(charHolder)); return Object.entries(charHolder).reduce((ac,[k,v]) =>v === max ? ac + k : ac, ''); } console.log(mostCommonCharacter("abbbcddefffg"))

You could accomplish this with a simple change.您可以通过简单的更改来完成此操作。 Just add the letter to "letters" if it is equal to "highest_num".如果它等于“highest_num”,只需将字母添加到“letters”。

  let highest_num = 0;
  let letters = "";
  for (const key in charHolder) {
    if (charHolder[key] > highest_num) {
      highest_num = charHolder[key];
      letters = key;
    } else if (charHolder[key] === highest_num) {
      letters += key;
    }
  }

Please find a more compact approach where you can use Array.prototype.reduce to get the {letter: frequency} map in an object from the string after splitting it into an array.请找到一种更紧凑的方法,您可以使用Array.prototype.reduce在将字符串拆分为数组后从字符串中获取对象中的 {letter: frequency} 映射。

Then use the Object.entries to get the most frequent and second frequent letters after sorting the entries of [key, values]:然后使用Object.entries对 [key, values] 的条目进行排序后得到最频繁和第二频繁的字母:

 const x = mostCommonCharacter("abbbcddefffg"); function mostCommonCharacter(str){ const dict = str.split("").reduce((acc, ele) =>{ acc[ele] = (acc[ele] || 0) + 1; return acc; }, {}); const letters = Object.entries(dict).sort((a, b) => b[1] - a[1]).map(a => a[0]); return letters.length > 1 ? letters.slice(0, 2).join("") : letters.length > 0 ? letters[0] : null; } console.log(x);

A solution involving an algorithmic approach using hashmaps .一种涉及使用hashmaps的算法方法的解决方案。

 var a = 'abbbcddefffg'; const counter = (str) => { var ch = {}; for(var i=0; i<str.length;i++) { if(str[i] in ch) { ch[str[i]] += 1 } else { ch[str[i]] = 1 } } return ch; } let sorted = (list) => Object.fromEntries(Object.entries(list).sort( (a,b) => b[1] - a[1] )) let counterInSorted = sorted(counter(a)); let getXMostOccuring = (stringObj, x) => { return Object.keys(stringObj).slice(0,x).join(''); } console.log('First x elements occuring frequently'); console.log(getXMostOccuring(counterInSorted,2)); console.log(sorted(counter(a)))

This approach will provide with the frequency of each character in a sorted manner.这种方法将以排序的方式提供每个字符的频率。 You can now decide to get 'x' most occurring characters.您现在可以决定获取 'x' 个最常出现的字符。

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

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