![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
JavaScript array: Find all elements that appear more than n times
We have an array of Number/String literals that contains some repeated entries. Our job is to write a function that takes in a positive integer Number n and returns a subarray of all the elements that makes appearance more than or equal to the number n specified by the only argument.
Therefore, let's write the code for this function −
We will use a Map() to keep count of the frequency of elements and later return the elements that exceed the specified count. The code for this will be −
Example
const arr = [34, 6, 34, 8, 54, 7, 87, 23, 34, 6, 21, 6, 23, 4, 23]; const moreThan = (arr, num) => { const creds = arr.reduce((acc, val) => { let { map, res } = acc; const count = map.get(val); if(!count && typeof count !== 'number'){ map.set(val, 1); }else if(num - count <= 1){ res.push(val); } else { map.set(val, count+1); }; return {map, res}; }, { map: new Map(), res: [] }); return creds.res; }; console.log(moreThan(arr, 3));
Output
The output in the console will be −
[34, 6, 23]
Advertisements