How to find the most repeated character in a string with Node.js

1 Answer

0 votes
function getMostRepeatedChar(str) { 
    // Create an object to store character frequencies
    const charCount = {};

    // Iterate through the string and count each character
    for (let char of str) {
        charCount[char] = (charCount[char] || 0) + 1;
    }

    // Find the character with the highest frequency
    let maxChar = '';
    let maxCount = 0;
    for (let char in charCount) {
        if (charCount[char] > maxCount) {
            maxChar = char;
            maxCount = charCount[char];
        }
    }

    return maxChar;
} 
 
const s = "c++nodejsjavascriptcphpc#";
    
console.log(getMostRepeatedChar(s));
 
   
   
/*
run:
   
c
   
*/

 



answered Nov 30, 2024 by avibootz
...