Problem
- Complete the function to find the count of the most frequent item of an array.
- 배열에서 가장 빈번한 item의 수를 반환한다.
- For an empty array return 0.
Solution 01
function mostFrequent(arr) {
let count = 0;
let frequentCount = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] === arr[j]) {
count++;
}
if (count > frequentCount) {
frequentCount = count;
}
}
count = 0;
}
return frequentCount;
}
mostFrequent([]); // 0
mostFrequent([4, 2, 9, 4]); // 2
mostFrequent([8, 6, 8, 8]); // 3
Solution 02
function mostFrequent(arr) {
let frequency = {};
let max = 0;
for (let i = 0; i < arr.length; i++) {
frequency[arr[i]] = frequency[arr[i]] ? frequency[arr[i]] + 1 : 1;
if (max < frequency[arr[i]]) {
max = frequency[arr[i]];
}
}
return max;
}
mostFrequent([]); // 0
mostFrequent([4, 2, 9, 4]); // 2
mostFrequent([8, 6, 8, 8]); // 3
Solution 03
function mostFrequent(arr) {
if (arr.length) {
let frequency = {};
let max = 0;
for (let i = 0; i < arr.length; i++) {
frequency[arr[i]] = (frequency[arr[i]] || 0) + 1
if (max < frequency[arr[i]]) {
max = frequency[arr[i]];
}
}
return max;
}
return 0;
}
mostFrequent([]); // 0
mostFrequent([4, 2, 9, 4]); // 2
mostFrequent([8, 6, 8, 8]); // 3