Computer >> Computer tutorials >  >> Programming >> Javascript

Return the element that appears for second most number of times in the array JavaScript


We are required to write a JavaScript function that takes in an array of literals. The function should return the element that appears for second most number of times in the array.

For example −

If the input array is −

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

Then the output should be −

const output = 2;

Example

const arr = [2, 5, 4, 3, 2, 6, 5, 5, 7, 2, 5];
const findSecondMost = (arr = []) => {
   const map={};
   arr.forEach(el => {
      if(map.hasOwnProperty(el)){
         map[el]++; }else{ map[el] = 1;
      }
   })
   const sorted = Object.keys(map).sort((a,b) => map[b]-map[a]);
   return sorted[1];
};
console.log(findSecondMost(arr));

Output

And the output in the console will be −

2