Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to remove every Nth element from an array JavaScript?
Removing every Nth element from an array is a common task in JavaScript. This can be accomplished using the Array.prototype.splice() method to modify the array in-place, or by creating a new array with the filtered elements.
Method 1: Using splice() (In-Place Modification)
The splice() method removes elements from the array and modifies the original array:
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
console.log("Original array:", arr);
const removeNth = (arr, n) => {
// Start from n-1 index and remove every nth element
// We need to go backwards to avoid index shifting issues
for(let i = arr.length - 1; i >= 0; i--) {
if((i + 1) % n === 0) {
arr.splice(i, 1);
}
}
};
removeNth(arr, 3);
console.log("After removing every 3rd element:", arr);
Original array: [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ] After removing every 3rd element: [ 'a', 'b', 'd', 'e', 'g', 'h', 'j' ]
Method 2: Using filter() (Creates New Array)
A more functional approach using filter() that doesn't modify the original array:
const originalArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
console.log("Original array:", originalArray);
const removeEveryNth = (arr, n) => {
return arr.filter((element, index) => (index + 1) % n !== 0);
};
const filteredArray = removeEveryNth(originalArray, 3);
console.log("New array (every 3rd removed):", filteredArray);
console.log("Original unchanged:", originalArray);
Original array: [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ] New array (every 3rd removed): [ 'a', 'b', 'd', 'e', 'g', 'h', 'j' ] Original unchanged: [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]
Practical Example with Numbers
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log("Original numbers:", numbers);
// Remove every 4th element (4, 8, 12)
const result = numbers.filter((num, index) => (index + 1) % 4 !== 0);
console.log("After removing every 4th:", result);
Original numbers: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] After removing every 4th: [ 1, 2, 3, 5, 6, 7, 9, 10, 11 ]
Comparison
| Method | Modifies Original | Performance | Use Case |
|---|---|---|---|
splice() |
Yes | Good for small arrays | When you want to modify in-place |
filter() |
No | Better for large arrays | When you want to keep original |
Conclusion
Use filter() for a functional approach that preserves the original array, or splice() when you need to modify the array in-place. The filter method is generally preferred for its immutability.
Advertisements
