We have multiple approaches to find smallest number with the highest frequency.
1. Using Object.entries :
const arr = [1, 3, 3, 4, 2, 3, 2, 5, 1, 4, 2];
const result = Object.entries(arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc
}, {})).reduce((a, b) => b[1] > a[1] || (b[1] === a[1] && Number(b[0]) < Number(a[0])) ? b : a)[0]
console.log(Number(result));
Output: 2
Explaination:
We got output as 2 because 2 appeared three times (2’s frequency is three). for 3 also we are having frequency three. But we need to find the smallest number with the highest frequency. So Answer is 2.
arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc
}, {})
Above code gives output as { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }. Here this object is in the form of key, value pairs, Where Keys are the given numbers in the array and values are their counts. acc[val] || 0 returns undefined values as 0 and + 1 increments the count.
When we wrap the above code inside Object.entries, it returns an Array of arrays as follows. [ [ ‘1’, 2 ], [ ‘2’, 3 ], [ ‘3’, 3 ], [ ‘4’, 2 ], [ ‘5’, 1 ] ]
Finally we are finding highest frequency. If multiple numbers have the same frequency then we are choosing the smallest number by applying the reduce method.
const arr = [1, 3, 3, 4, 2, 3, 2, 5, 1, 4, 2];
const result = Object.entries(arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc
}, {})).reduce((a, b) => b[1] > a[1] || (b[1] === a[1] && Number(b[0]) < Number(a[0])) ? b : a)
console.log(result);
Output : [ '2', 3 ]
Above code gives output as [ ‘2’, 3 ]. From here we need to extract the value 2. So we are using [0]. and it will give ‘2’ and then finally we are converting string to number by using console.log(Number(result)).
2. Using step by step Approach :
const arr = [1, 3, 3, 4, 2, 3, 2, 5, 1, 4, 2];
let freq = {};
for(let num of arr) {
freq[num] = (freq[num] || 0) + 1;
}
let maxFreq = Math.max(...Object.values(freq));
let result = Math.min(...Object.keys(freq).filter(key => freq[key] === maxFreq).map(Number))
console.log(result);
Output: 2
The following code counts frequency and gives this output : { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }
let freq = {};
for(let num of arr) {
freq[num] = (freq[num] || 0) + 1;
}
Next we will find max frequency which is 3 with the following line of code
let maxFreq = Math.max(...Object.values(freq));
Finally we will filter by max frequency and find smallest number with the following code.
let result = Math.min(...Object.keys(freq).filter(key => freq[key] === maxFreq).map(Number))