-
Notifications
You must be signed in to change notification settings - Fork 0
/
6kyu-highest-rank-number-in-an-array.js
29 lines (24 loc) · 1.13 KB
/
6kyu-highest-rank-number-in-an-array.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
// Write a method highestRank(arr) (or highest-rank in clojure) which returns the number which is most frequent in the given input array (or ISeq). If there is a tie for most frequent number, return the largest number of which is most frequent.
// Example:
// arr = [12, 10, 8, 12, 7, 6, 4, 10, 12];
// highestRank(arr) //=> returns 12
// arr = [12, 10, 8, 12, 7, 6, 4, 10, 12, 10];
// highestRank(arr) //=> returns 12
// arr = [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10];
// highestRank(arr) //=> returns 3
function highestRank(arr) {
let sorted = arr.sort((a, b) => a - b);
let result = 0;
let length = 0;
for (let i = 0; i < sorted.length; i += 1) {
if (sorted.lastIndexOf(sorted[i]) - sorted.indexOf(sorted[i]) > length) {
result = sorted[i];
length = sorted.lastIndexOf(sorted[i]) - sorted.indexOf(sorted[i])
i = sorted.lastIndexOf(sorted[i]);
} else if (sorted.lastIndexOf(sorted[i]) - sorted.indexOf(sorted[i]) === length) {
result > sorted[i] ? result = result : result = sorted[i];
i = sorted.lastIndexOf(sorted[i]);
}
}
return result;
}