I want to create a function that will return the number with highest frequency(mode). For example: if array contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode, I want to return the one that appeared in the array first (ie. [10,2,5, 4, 5, 2, 4] should return 2 because it appeared first. If there is no mode, I want to return -1. The array will not be empty. Below is my attempt
JavaScript
x
33
33
1
function Mode(arr){
2
if(arr == undefined || arr.length == 0){
3
return
4
}
5
const number_to_frequency = {};
6
let number_with_overall_highest_frequency = 0;
7
let overall_highest_frequency = 0;
8
9
for(index in arr) {
10
const number = arr[index];
11
12
if(number_to_frequency[number]) {
13
number_to_frequency[number] += 1;
14
} else {
15
number_to_frequency[number] = 1;
16
}
17
18
let updated_frequency = number_to_frequency[number]
19
20
if(overall_highest_frequency < updated_frequency) {
21
number_with_overall_highest_frequency = number;
22
overall_highest_frequency = updated_frequency;
23
}
24
25
}
26
27
if(overall_highest_frequency == 1){
28
return -1
29
}
30
return number_with_overall_highest_frequency;
31
};
32
console.log(Mode([10,2,5, 4, 5, 2, 4])) //5
33
Advertisement
Answer
If you only need the first one that its repeated you can try this approach
JavaScript
1
10
10
1
const checkMode = (array = []) => {
2
3
const duplicated = array.find(value => array.filter(_value => value === _value).length > 1)
4
5
return duplicated >= 0 ? duplicated: -1
6
}
7
8
checkMode([10,2,5, 4, 5, 2, 4])
9
10