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
How to remove certain number elements from an array in JavaScript
We are required to write a function that takes in an array of numbers and a number, and it should remove all the occurrences of that number from the array in-place.
Let's explore different approaches to accomplish this task effectively.
Method 1: Using Recursion with splice()
We can use recursion to remove elements by finding and splicing them one by one. The recursive function continues until no more occurrences are found.
const numbers = [1, 2, 0, 3, 0, 4, 0, 5];
const removeElement = (arr, element) => {
if(arr.indexOf(element) !== -1){
arr.splice(arr.indexOf(element), 1);
return removeElement(arr, element);
}
return;
};
removeElement(numbers, 0);
console.log(numbers);
[ 1, 2, 3, 4, 5 ]
Method 2: Using filter() (Non-destructive)
The filter() method creates a new array with elements that don't match the target value:
const numbers = [1, 2, 0, 3, 0, 4, 0, 5];
const filteredNumbers = numbers.filter(num => num !== 0);
console.log("Original:", numbers);
console.log("Filtered:", filteredNumbers);
Original: [ 1, 2, 0, 3, 0, 4, 0, 5 ] Filtered: [ 1, 2, 3, 4, 5 ]
Method 3: Using a While Loop (In-place)
A while loop approach that modifies the original array:
const numbers = [1, 2, 0, 3, 0, 4, 0, 5];
const removeElementLoop = (arr, element) => {
let index = arr.indexOf(element);
while(index !== -1) {
arr.splice(index, 1);
index = arr.indexOf(element);
}
};
removeElementLoop(numbers, 0);
console.log(numbers);
[ 1, 2, 3, 4, 5 ]
Method 4: Reverse Iteration (Most Efficient In-place)
Iterating backwards prevents index shifting issues when removing elements:
const numbers = [1, 2, 0, 3, 0, 4, 0, 5];
const removeElementReverse = (arr, element) => {
for(let i = arr.length - 1; i >= 0; i--) {
if(arr[i] === element) {
arr.splice(i, 1);
}
}
};
removeElementReverse(numbers, 0);
console.log(numbers);
[ 1, 2, 3, 4, 5 ]
Comparison
| Method | Modifies Original | Performance | Best Use Case |
|---|---|---|---|
| Recursion | Yes | Slower | Learning recursion |
| filter() | No | Fast | Functional programming |
| While Loop | Yes | Moderate | Simple in-place removal |
| Reverse Iteration | Yes | Fastest | Efficient in-place removal |
Conclusion
Use filter() for functional programming approaches, or reverse iteration for efficient in-place removal. The recursive method works but is less efficient for large arrays.
