DEV Community

Discussion on: JS Coding Question #9: Get Max Character In A String [Challenging]

Collapse
inhuofficial profile image
InHuOfficial • Edited on

The only issue with your example is the double loop, you can achieve the same with the following which takes advantage of how split works:

99% sure it returns the same as your function.

Collapse
frontendengineer profile image
Let's Code Author • Edited on

thank you for this solution! Learned something today. I took your example and translate it to more readable form.

function getMaxChar(str){
  let max = 0
  let maxChar = ''
  const normalizedString = str.toLowerCase().replace(/[^a-z']/g, "")

  normalizedString.split('')
    .forEach(char => {
      if (normalizedString.split(char).length > max) {
          max = normalizedString.split(char).length;
          maxChar = char;
       }
    })

  return maxChar;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
inhuofficial profile image
InHuOfficial

Yeah sorry, I already had the main part of the function as part of a code snippets library and it is partially minimised due to a mistake I made...I have about 100 snippets that aren't very readable like that!

I have copied the normalisedString.split() etc. part back into my code snippets library so it is readable again, so thanks for that 😀

Maybe I will finally get around to fixing them all as they do come in handy and it just laziness stopping me fixing them!

Thread Thread
frontendengineer profile image
Let's Code Author

LOL dude, nothing to apologize from. You actually improved my solution helping out myself and other folks who will read this post. So thank you and I am glad that you came in and share that snippet. 👍

Some comments have been hidden by the post's author - find out more