-
Notifications
You must be signed in to change notification settings - Fork 1
/
mostCommon.js
42 lines (33 loc) · 1.16 KB
/
mostCommon.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
const mostCommon = (arrayOfStrings) => {
const map = {};
let maxFreqCount = 0;
let maxFreqString = arrayOfStrings[0];
let output = "";
if (arrayOfStrings.length === 0) {
output = `"Sorry. The input array is empty"`;
} else {
for (let index = 0; index < arrayOfStrings.length; index++) {
const element = arrayOfStrings[index];
if (map[element]) {
map[element]++;
} else {
map[element] = 1;
}
if (map[element] > maxFreqCount) {
maxFreqCount = map[element];
maxFreqString = element;
}
}
output = maxFreqString;
}
return output;
};
const inputArrayOfStrings1 = ["j", "k", "k", "l", "m", "n", "o"];
const inputArrayOfStrings2 = ["ijk", "ijk", "xyz", "xyz", "ijk", "opr", "stu"];
const inputArrayOfStrings3 = [];
const output1 = mostCommon(inputArrayOfStrings1);
const output2 = mostCommon(inputArrayOfStrings2);
const output3 = mostCommon(inputArrayOfStrings3);
console.log(`Input string: ${inputArrayOfStrings1}. Result: ${output1}`);
console.log(`Input string: ${inputArrayOfStrings2}. Result: ${output2}`);
console.log(`Input string: ${inputArrayOfStrings3}. Result: ${output3}`);