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', ','
]

Updated on: 26-Aug-2020

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements