OneBite.Dev - Coding blog in a bite size

How to find the maximum character in a string in javascript

Here is an efficient way to find the maximum character in a string (the character that appears most frequently) and count how many times it appears.

We’ll use a JavaScript object as a map to count occurrences of each character, then find the character with the maximum count.

WARNING Note that if there are multiple characters with the same maximum count, this function will return the first one it encounters.

Code solution

function maxCharInString(str) {
  let charMap = {};
  let maxChar = '';
  let maxCount = 0;

  // Build character map
  for(let char of str) {
    charMap[char] = charMap[char] + 1 || 1;
  }

  // Find character with maximum count
  for(let char in charMap) {
    if(charMap[char] > maxCount) {
      maxCount = charMap[char];
      maxChar = char;
    }
  }

  return {maxChar, maxCount};
}

let result = maxCharInString("javascript");
console.log(result.maxChar); // Prints: a
console.log(result.maxCount); // Prints: 2

Explanation

In the maxCharInString function, we first iterate over the string to build a character map where the keys are the characters and the values are the counts.

Then we iterate over the character map to find the character with the maximum count. The function returns an object with the maximum character and its count.

← How to check if string is...
fizz buzz program sample ... →
javascript