- Trending Categories
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
How to remove every Nth element from an array JavaScript?
Let’s say, we have to write a function remove Nth that takes in an array and a number n and it removes every nth element of the array in place.
This can be done using the Array.prototype.splice() method and here is the code for doing so −
Example
const arr = ['T','h','a','i','s','b',' ','i','c','s',' ','a','t','h','e','e',' ','t','s','o','r','n','g','t',' ','t','n','h','a','s','t',' ','o','n','e','o','v','e','a','r',' ','f','e','n','a','d','s','p',',']; const removeNth = (arr, n) => { for(let i = n-1; i < arr.length; i += n){ arr.splice(i, 1); }; }; removeNth(arr, 2); console.log(arr);
Output
The output in the console will be −
[ 'T', 'a', 'i', 'b', ' ', 'c', 's', 'a', 't', 'e', 'e', 't', 's', 'r', 'n', 't', ' ', 'n', 'h', 's', 't', 'o', 'n', 'o', 'v', 'a', 'r', 'f', 'e', 'a', 'd', 'p', ',' ]
Advertisements