- Trending Categories
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 most frequent number in the array and how many times it is repeated in JavaScript
We are required to write a JavaScript function that takes in an array of literals and finds the most frequent number in the array and how many times it is repeated.
Example
The code for this will be −
const arr = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3']; const findFrequency = (arr = []) => { const count = {}; const max = arr.reduce((acc, val, ind) => { count[val] = (count[val] || 0) + 1; if (!ind || count[val] > count[acc[0]]) { return [val]; }; if (val !== acc[0] && count[val] === count[acc[0]]) { acc.push(val); }; return acc; }, undefined); return { max, count }; } console.log(findFrequency(arr));
Output
And the output in the console will be −
{ max: [ '4' ], count: { '1': 3, '2': 2, '3': 2, '4': 5, '9': 1, '13': 1 } }
Advertisements