w3resource

JavaScript: Find the most frequent character in a string

JavaScript String: Exercise-58 with Solution

Write a JavaScript program to find the most frequent character in a given string.
Test Data:
("Madam") -> "a"
("civic") -> "c"
("HellloL223LLL") -> "L"
(12321) -> "It must be a string."

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to find the most frequent character in a string</title>
</head>
<body>

</body>
</html>

JavaScript Code:

const test = (str) => { 
   if (str.length === 0) 
    {
    return 'String should not be empty!'
   }
    if (typeof str !== 'string')
     {
       return 'It must be a string.'
     }
  const occurrence_Map = new Map()

  for (const char of str) 
    {
      occurrence_Map.set(char, occurrence_Map.get(char) + 1 || 1)
    }

  // find the max char from the occurrence map
  let max_char = { char: '', occur: -Infinity }

  for (const [char, occur] of occurrence_Map) {
    if (occur > max_char.occur) {
      max_char = { char,occur }
    }
  }

  return max_char.char
}
console.log(test("Madam"))
console.log(test("civic"))
console.log(test("HellloL223LLL"))
console.log(test(12321))

Sample Output:

a
c
L
It must be a string.

Flowchart:

Flowchart: JavaScript: Find the most frequent character in a string

Live Demo:

See the Pen javascript-string-exercise-58 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Rearrange a string to become a palindrome.
Next: Find the most frequent word in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.