0

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-e.i, the "a" in "javascript" which appears twice and the rest of the characters appear only once. But if the string is 'javascript prototype', there are two characters that appear the most which are "p" and "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. I expected the output to be "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);

1 Answer 1

2

Find the max number in the charMap by spreading the Object.values() into Math.max(). Then use Array.filter() to get just the keys that have the max value, and join them with a space:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.