- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Changing an array in place using splice() JavaScript
We are required to write a function that, given an array arr and a number n, returns the array with elements repeating no more than n times. And we have to do all this without disturbing the indices of desired elements. So, let’s write the code for this function,
We will keep the count of all the elements in a hashmap and during iteration whenever the count of any element exceeds the maximum count we will splice that element. The code for this will be −
Example
const arr = [7, 26, 21, 41, 43, 2, 26, 24, 10, 26, 10, 10, 24, 35, 35, 35, 43, 26, 41, 7, 24, 24, 21, 24, 10, 35, 10, 7, 24, 7, 35, 26, 41, 35, 2, 43, 24, 2, 41, 26, 41, 7, 7, 26, 2, 10, 43, 10, 35, 41, 24, 7, 2, 2, 7, 2, 26, 24, 26, 43, 43, 21, 10, 28, 10]; const array = [12, 4, 2, 12, 32, 21, 67, 4, 32, 5]; const deleteExtra = (arr, n) => { const map = {}; for(let i = 0; i < arr.length; i++){ if(map[arr[i]]){ if(map[arr[i]] >= n){ arr.splice(i, 1); i--; }else{ map[arr[i]]++; } continue; }; map[arr[i]] = 1; } }; deleteExtra(array, 1); deleteExtra(arr, 2); console.log(array); console.log(arr);
Output
The output in the console will be −
[ 12, 4, 2, 32, 21, 67, 5 ] [ 7, 26, 21, 41, 43, 2, 26, 24, 10, 10, 24, 35, 35, 43, 41, 7, 21, 2, 28 ]
- Related Articles
- Remove elements from array in JavaScript using includes() and splice()?
- How to splice duplicate item in array JavaScript
- How to remove elements using the splice() method in JavaScript?
- Sort an integer array, keeping first in place in JavaScript
- How to change an object Key without changing the original array in JavaScript?
- Adding an element in an array using Javascript
- Sort an array and place a particular element as default value in JavaScript
- Changing the case of a string using JavaScript
- Low level difference between Slice and Splice methods in Javascript
- Reversing array without changing the position of certain elements JavaScript
- Finding Fibonacci sequence in an array using JavaScript
- Third smallest number in an array using JavaScript
- Changing color randomly in JavaScript
- Finding product of an array using recursion in JavaScript
- Maximum length of mountain in an array using JavaScript

Advertisements