In my task I have to write a program that finds the most frequent number in an array and how many time it is repeated. I wrote something, but only prints the max number of repeating time. So my question is how can I print the value of this element(max number)(in my case is 4)? :)
var array = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
function frequentNumber(arr) {
var result = [],
result2 = [];
sorted_arr = arr.sort();
console.log(sorted_arr);
n=1;
buffer = [];
for (var i = 0; i < sorted_arr.length; i++) {
if (sorted_arr[i + 1] === sorted_arr[i]) {
n++;
}else{
if(buffer.length != 0 ){
for(var j = 0; j < buffer.length; j++){
if(buffer[j] < n){
result = sorted_arr[j] + " is " + n;
}
}
}else{buffer.push(n)}
n=1;
}
}
// console.log(Math.max.apply(Math, buffer));
console.log(buffer);
}
frequentNumber(array);
You can use .reduce to create an object with the numbers and the times they're listed - then simply iterate the object and find the highest value:
var ranks = array.reduce(function(totals, num) {
if (!totals[num]) totals[num] = 0;
totals[num]++;
return totals;
}, {});
//Iterate and find
var max = 0;
Object.keys(ranks).forEach(function(num) {
if (ranks[num] > max) {
max = num;
}
});
console.log(max); //4 - number
console.log(ranks[max]); //5 - times repeated
This doesn't take numbers with the same count into play - whichever number is iterated in the object first with the highest count will be the result - and since objects are unordered, a same count could have different results over multiple executions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With