Find Second most frequent character in array - JavaScript


We are required to write a JavaScript function that takes in a string and returns the character from the string that appears for the second most number of times.

Let’s say the following is our array −

const arr = [1, 34, 4, 3, 2, 1, 4, 6, 4, 6, 5, 3, 6, 6];

So, the frequent character appearing is −

6

But we want the output to be the second most frequent character i.e.

4

Let’s write the code for this function −

Example

const arr = [1, 34, 4, 3, 2, 1, 4, 6, 4, 6, 5, 3, 6, 6];
const secondMostFrequent = arr => {
   const map = arr.reduce((acc, val) => {
      if(acc.has(val)){
         acc.set(val, acc.get(val) + 1);
      }else{
         acc.set(val, 1);
      };
      return acc;
   }, new Map);
   const frequencyArray = Array.from(map);
   return frequencyArray.sort((a, b) => {
      return b[1] - a[1];
   })[1][0];
};
console.log(secondMostFrequent(arr));

Output

Following is the output in the console −

4

Updated on: 14-Sep-2020

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements