-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecond-Max-Occurance.js
More file actions
45 lines (37 loc) · 957 Bytes
/
Second-Max-Occurance.js
File metadata and controls
45 lines (37 loc) · 957 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function secondMaxOccurance(arr) {
var newObj = {};
for (let i = 0; i < arr.length; i++) {
if (newObj[arr[i]]) {
newObj[arr[i]] += 1;
} else {
newObj[arr[i]] = 1;
}
}
var max = 0;
var secondMax = 0;
for (let item in newObj) {
if (max === 0 && secondMax === 0) {
max = newObj[item];
}
if (newObj[item] > max) {
secondMax = max;
max = newObj[item];
} else if (newObj[item] > secondMax && newObj[item] < max) {
secondMax = newObj[item];
}
// else {
// secondMax = newObj[item];
// }
}
var filteredData = Object.keys(newObj).filter((data) => {
return newObj[data] === secondMax;
});
console.log(newObj);
return filteredData.length > 0
? filteredData
: "No Second Max Data Available";
}
var arr = ["aaa", "ccc", "bbb"];
console.log(secondMaxOccurance(arr));
var str = "abacdeabgsbdsabcba";
console.log(secondMaxOccurance(str.split("")));