

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 ]
- Related Questions & Answers
- Deleting occurrences of an element if it occurs more than n times using JavaScript
- JavaScript array: Find all elements that appear more than n times
- The n times dribbling strings in JavaScript
- Limiting duplicate character occurrence to once in JavaScript
- Is element repeated more than n times in JavaScript
- Limiting string up to a specified length in JavaScript
- Finding number of occurrences of the element appearing most number of times in JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Repeating tuples N times in Python
- Calculate n + nn + nnn + ? + n(m times) in Python
- Python Program to calculate n+nm+nmm.......+n(m times).
- Sum of two elements just less than n in JavaScript\n
- Program to rotate a string of size n, n times to left in Python
- Calculate n + nn + nnn + … + n(m times) in Python program
- Calculate n + nn + nnn + u + n(m times) in Python Program
Advertisements