
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Get the item that appears the most times in an array JavaScript
- Take an array and find the one element that appears an odd number of times in JavaScript
- Finding number that appears for odd times - JavaScript
- First element that appears even number of times in an array in C++
- Find the second most frequent element in array JavaScript
- Find the element that appears once in sorted array - JavaScript
- How to find the one integer that appears an odd number of times in a JavaScript array?
- Finding number of occurrences of the element appearing most number of times in JavaScript
- Find the only element that appears b times using C++
- Find the element that appears once in an array where every other element appears twice in C++
- Number of times a string appears in another JavaScript
- Return the index of first character that appears twice in a string in JavaScript
- Find Second most frequent character in array - JavaScript
- Find the most frequent number in the array and how many times it is repeated in JavaScript
- Finding the second most frequent character in JavaScript

Advertisements