- 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
Limiting elements occurrences to n times in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers, arr, that may contain duplicates as the first argument, and a number, num, as the second and final argument.
The task of our function is to iterate through the array and check whether there exists some number that appears for more than n times in the array.
If there exists any such element, we should delete its extra occurrences to limit its occurrence to at most num.
For example, if the input to the function is −
Input
const arr = [4, 1, 3, 1, 4, 1, 3, 4, 2]; const num = 2;
Output
const output = [4, 1, 3, 1, 4, 3, 2];
Output Explanation
Both 4 and 1 appeared thrice, so their third appearance is deleted
Example
Following is the code −
const arr = [4, 1, 3, 1, 4, 1, 3, 4, 2]; const num = 2; const deleteExtra = (arr = [], num = 1) => { if(num === 0){ return []; }; const res = []; const map = {}; for(let i = 0; i < arr.length; i++){ const el = arr[i]; map[el] = (map[el] || 0) + 1; if(map[el] <= num){ res.push(el); }; }; return res; }; console.log(deleteExtra(arr, num));
Output
[ 4, 1, 3, 1, 4, 3, 2 ]
Advertisements
To Continue Learning Please Login
Login with Google