- Related Questions & Answers
- Array elements that appear more than once?
- Array elements that appear more than once in C?
- Is element repeated more than n times in JavaScript
- Elements that appear twice in array in JavaScript
- Deleting occurrences of an element if it occurs more than n times using JavaScript
- Frequency of elements of one array that appear in another array using JavaScript
- Limiting elements occurrences to n times in JavaScript
- Sum of two elements just less than n in JavaScript\n
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- Find maximum N such that the sum of square of first N natural numbers is not more than X in Python
- Return a subarray that contains all the element from the original array that are larger than all the elements on their right in JavaScript
- Find array elements that are out of order in JavaScript
- Find a range that covers all the elements of given N ranges in C++
- Finding the element larger than all elements on right - JavaScript
- How to print all students name having percentage more than 70% in JavaScript?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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));

The output in the console will be −

[34, 6, 23]

Advertisements