- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the second most frequent element 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.
Example
The code for this will be −
const arr = [5, 2, 6, 7, 54, 3, 2, 2, 5, 6, 7, 5, 3, 5, 3, 4]; 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
The output in the console −
2
Advertisements