let obj1 = { 1:1,2:1,4:3};
I want to get the property 4 as the output because the value of that property is highest of all other properties. I am trying to find out the highest frequency number in my own way.
let arr1 = [1, 2, 3, 4, 4, 4, 5];
let arr1Obj = {};
function findMaxFreq(arr, arr1Obj) {
let freqArr = [];
let objarrvalue = 0;
for (let i = 0; i < arr.length; i++) {
let frequencyOf = arr[i];
let count = 1;
for (let j = arr[i]; j < arr.length; j++) {
if (arr[i] === arr[j]) {
count++;
} else {
break;
}
}
arr1Obj[arr[i]] = count;
}
let objvalues = Object.values(arr1Obj);
for (let i = 0; i < objvalues.length; i++) {
if (objvalues[i] > objarrvalue) {
objarrvalue = objvalues[i];
}
}
return objarrvalue;
}
console.log(findMaxFreq(arr1, arr1Obj));
4
Answers
I believe if I can get your question correct, you want to get the maximum occurring number of a given array, say number 4 appeared more than 3 times than any other number.
Here is how you can achieve that:
I added a lot of comments to help you understand how I solved it.
You could do it like that:
If the input array is sorted:
you can use
cache
technique in this case like this:You could take a single loop with an array for collecting max frequency values, because of the possibillity of having two or more values with same frequency.
At then end return either a single value, if only one value is available or an array of values.