JavaScript program that returns the character that appears the most in a string
Posted by SceDev
Last Updated: February 27, 2024

Write a JavaScript program that returns the character that appears the most in a string.

Code:

function findMostFrequentCharacter(str) {
    const charMap = {};
    let result = '';
    let resultCount = 0;
  
    str.split('').forEach(char => {
      charMap[char] = charMap[char] + 1 || 1;
      if (charMap[char] > resultCount) {
        result = char;
        resultCount = charMap[char];
      }
    });
  
    return result;
  }
  
var result = findMostFrequentCharacter('helloworld');
 
console.log(result);