

- 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
Deleting occurrences of an element if it occurs more than n times using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument.
Our function should delete elements from the array so that the resulting array contains no element appearing for more than the specified number (second argument).
Example
Following is the code −
const arr = [4, 2, 3, 2, 4, 2, 2, 4]; const num = 2; const deleteExcess = (arr = [], num = 1) => { const map = {}; for(let i = 0; i < arr.length; i++){ if(!map[arr[i]]){ map[arr[i]] = 1; }else if(map[arr[i]] + 1 <= num){ map[arr[i]]++ }; }; const res = []; Object.keys(map).forEach(key => { for(i = 0; i < map[key]; i++){ res.push(key); }; }); return res.map(Number); }; console.log(deleteExcess(arr, num));
Output
[ 2, 2, 3, 4, 4 ]
- Related Questions & Answers
- Is element repeated more than n times in JavaScript
- JavaScript array: Find all elements that appear more than n times
- Limiting elements occurrences to n times in JavaScript
- Python - Check if k occurs atleast n times in a list
- Using more than one CSS classes for an element in HTML
- Finding number of occurrences of the element appearing most number of times in JavaScript
- Display records with more than two occurrences in MySQL?
- Find the number of times a value of an object property occurs in an array with JavaScript?
- Which event occurs in JavaScript when the dragging of an element begins?
- Adding digits of a number using more than 2 methods JavaScript
- How to match n number of occurrences of an expression using Java RegEx?
- Which event occurs in JavaScript when an element is getting dragged?
- Which event occurs in JavaScript when an element is dragged completely?
- Remove all occurrences of a multiple occurring element in an array in JavaScript
- Explain deleting an element in a queue by using C language
Advertisements