Given an array of numbers, I have to find the number with the highest frequency and return it. If there are two or more numbers with the same highest frequency then I need to return the biggest number.
Below is the code I’ve written..
const numbers = [1, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 6, 7, 5];
const numArr = [12, 20, 5, 4, 10, 10, 10, 5, 4, 5, 3, 2];
function frequency(array) {
let object = {}
let maxCount = 0;
let result = 0;
for (let num of array) {
if (object.hasOwnProperty(num)) {
object[num] = object[num] + 1;
}
else object[num] = 1;
}
console.log(object)
let entry = Object.entries(object)
for (const [key, val] of entry) {
if (maxCount < val) {
maxCount = val;
result = key;
}
}
for (const [key, val] of entry) {
result = maxCount === val && key > result ? key : result;
}
return [result, maxCount];
}
const [res, count] = frequency(numArr);
console.log(`number with highest freq: ${res}nfrequency: ${count}`)
Function frequency
is working with arrays containing single-digit numbers (e.g numbers
). But it’s not giving correct output with arrays containing double-digit numbers (e.g numArr
)
The above code should output 10
as the number with highest frequency and 3
as its frequency. But it outputs 5
and 3
respectively. Why is that? Is this related to ASCII values? Thankyou for your time.
3
Answers
The keys are already sorted, and if you want the highest "result", you need to change
maxCount < val
tomaxCount <= val,
where a higher key will replace a lower key when the frequencies are the same.Also, you don’t need the last loop. It does nothing but messing up your code.
Finally, you should be able to solve this problem using only one loop.
Keys in objects are always strings or symbols, never numbers. For most of your code, that’s fine, but it’s a problem in your two
for-of
loops overObject.entries
, sincekey
there will be a string, and you end up settingresult
to a string. In the second loop, thekey > result
is a string comparison, which compares digit-by-digit, not numerically.Instead of using an object for your counts, use a
Map
.Map
keys can be actual numbers. See MDN’s article onMap
for guidelines for when to use objects vs. maps.You need only 1 loop here, just compare with the max while collecting the counts. That way you also don’t need to care about number/string conversion for the result: