-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindMaxCharacter.js
More file actions
31 lines (23 loc) · 831 Bytes
/
FindMaxCharacter.js
File metadata and controls
31 lines (23 loc) · 831 Bytes
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
// CHALLENGE: MAX CHARACTER
// Return the character that is most common in a string
// ex. maxCharacter('javascript') == 'a'
// SOLUTION: hashMap
// Using object as a hashmap(key: character, value: count)
// Then returning the char which is most common.
const maxCharacter = (str) => {
let hashMap = {};
str.split("").forEach((chr) => {
if (!hashMap.hasOwnProperty(chr)) {
hashMap[chr] = 1;
} else {
hashMap[chr]++;
}
});
// Object.keys returns key values as an array
// we need to initialize as 0 in reduce function.
const max = Object.keys(hashMap).reduce((a, k) => Math.max(a, hashMap[k]), 0);
const resultArr = Object.keys(hashMap).filter((k) => hashMap[k] === max);
return resultArr;
};
console.log(maxCharacter("javascript"));
console.log(maxCharacter("javascriptisawesome"));