-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxCharacterInString.js
50 lines (41 loc) · 1.07 KB
/
maxCharacterInString.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// CHALLENGE 5: MAX CHARACTER
// Return the character that is most common in a string
// ex. maxCharacter('javascript') == 'a'
function maxCharacter(str) {
const charMap = {};
let maxNum = 0;
let maxChar = '';
str.split('').forEach(function(char) {
if(charMap[char]) {
charMap[char]++;
} else {
charMap[char] = 1;
}
});
for(let char in charMap) {
// debugger;
if(charMap[char] > maxNum) {
maxNum = charMap[char];
maxChar = char;
}
}
return maxChar;
}
// //////////////
// const sortedStr = str.split('').sort();
// const maxChar = {char: '', count: 0};
// const currentChar = {char: '', count: 0};
// sortedStr.forEach(char => {
// if(currentChar.char === char){
// currentChar.count++;
// } else {
// if(maxChar.count < currentChar.count){
// maxChar.char = currentChar.char;
// maxChar.count = currentChar.count;
// }
// currentChar.char = char;
// currentChar.count = 0;
// }
// });
// return maxChar.char;
// }