function maxRecurringChar(text) {
let charMap = {};
let maxCharValue = 0;
let maxChar = '';
for (let char of text) {
if (charMap.hasOwnProperty(char)) {
charMap[char]++;
} else {
charMap[char] = 1;
}
}
for (let char in charMap) {
if (charMap[char] > maxCharValue) {
maxCharValue = charMap[char];
maxChar = char;
}
}
return maxChar;
}
Here is the code I don't understand, cause first for always will return 1 , if always will return 1 why do we need to write the first loop?
The algorithm creates a new Object charMap to which all characters of the String text will be added as attributes. In the first for-loop you either add a new attribute with the name of the current char and set the counted value to 1 or, if already present, increment the counted value if the char was already found in the string. So you effectivly count for every char the number of occurences.
In the second for-loop the Object is searched for the greatest counted value, which will be the char with the highest count of occurences.