How to find smallest number with the highest frequency in the array ? – JavaScript

We have multiple approaches to find smallest number with the highest frequency.

1. Using Object.entries :

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.

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.

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 :

The following code counts frequency and gives this output : { ‘1’: 2, ‘2’: 3, ‘3’: 3, ‘4’: 2, ‘5’: 1 }

Next we will find max frequency which is 3 with the following line of code

Finally we will filter by max frequency and find smallest number with the following code.


Discover more from Learners Store

Subscribe to get the latest posts sent to your email.

Leave a comment