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
Remove number from array and shift the remaining ones JavaScript
In this problem statement, our task is to write a function to remove numbers from an array and shift the remaining elements using JavaScript. We'll explore multiple approaches including the filter method, for loops, and in-place modification to achieve this functionality.
Understanding the Problem
We need to create a function that removes all occurrences of a given number from an array and shifts the remaining items to fill the gaps. For example, given array [1, 2, 3, 4, 2, 5] and number 2, the result would be [1, 3, 4, 5] with all instances of 2 removed and elements shifted left.
Using filter() Method
The filter() method creates a new array with elements that pass a test condition:
const arrayOfNumbers = [12, 22, 35, 44, 52, 35, 68];
const numberToRemove = 35;
const arrayWithoutNum = arrayOfNumbers.filter(function (number) {
return number !== numberToRemove;
});
console.log("Original Array:", arrayOfNumbers);
console.log("Array after removal:", arrayWithoutNum);
Original Array: [12, 22, 35, 44, 52, 35, 68] Array after removal: [12, 22, 44, 52, 68]
Using for Loop
Manual iteration with a for loop gives more control over the process:
const arrayOfNumbers = [12, 22, 35, 44, 52, 35, 68];
const numberToRemove = 35;
const arrayWithoutNum = [];
for (let i = 0; i < arrayOfNumbers.length; i++) {
if (arrayOfNumbers[i] !== numberToRemove) {
arrayWithoutNum.push(arrayOfNumbers[i]);
}
}
console.log("Original array:", arrayOfNumbers);
console.log("Array after removal:", arrayWithoutNum);
Original array: [12, 22, 35, 44, 52, 35, 68] Array after removal: [12, 22, 44, 52, 68]
In-Place Modification
For memory efficiency, we can modify the original array in-place:
function removeNumberInPlace(arr, numToRemove) {
let writeIndex = 0;
for (let readIndex = 0; readIndex < arr.length; readIndex++) {
if (arr[readIndex] !== numToRemove) {
arr[writeIndex] = arr[readIndex];
writeIndex++;
}
}
// Trim array to new length
arr.length = writeIndex;
return arr;
}
const numbers = [12, 22, 35, 44, 52, 35, 68];
console.log("Before:", numbers);
removeNumberInPlace(numbers, 35);
console.log("After in-place removal:", numbers);
Before: [12, 22, 35, 44, 52, 35, 68] After in-place removal: [12, 22, 44, 52, 68]
Comparison
| Method | Time Complexity | Space Complexity | Modifies Original |
|---|---|---|---|
| filter() | O(n) | O(n) | No |
| for loop | O(n) | O(n) | No |
| In-place | O(n) | O(1) | Yes |
Conclusion
The filter() method provides the cleanest solution for removing numbers from an array. Use in-place modification when memory efficiency is critical, and for loops when you need maximum control over the process.
