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
Remove elements from array in JavaScript using includes() and splice()?
The includes() method checks whether an array contains a specific element, while splice() is used to add or remove items from an array. Together, they can be used to remove multiple elements from an array efficiently.
Syntax
array.includes(searchElement) array.splice(start, deleteCount)
How It Works
The approach involves iterating through the array and using includes() to check if each element should be removed. When a match is found, splice() removes it, and the index is decremented to account for the array shift.
Example
deleteElementsFromArray = function(elements, ...values) {
let elementRemoved = Array.from(values);
for (var index = 0; index < elements.length; index++){
if (elementRemoved.includes(elements[index])){
elements.splice(index, 1);
index--;
}
}
return elements;
}
console.log(deleteElementsFromArray([80, 90, 56, 34, 79], 90, 34, 79));
Output
[ 80, 56 ]
Step-by-Step Breakdown
// Original array
let numbers = [80, 90, 56, 34, 79];
let toRemove = [90, 34, 79];
console.log("Original array:", numbers);
console.log("Elements to remove:", toRemove);
// Process each element
for (let i = 0; i < numbers.length; i++) {
if (toRemove.includes(numbers[i])) {
console.log(`Removing ${numbers[i]} at index ${i}`);
numbers.splice(i, 1);
i--; // Adjust index after removal
}
}
console.log("Final array:", numbers);
Output
Original array: [ 80, 90, 56, 34, 79 ] Elements to remove: [ 90, 34, 79 ] Removing 90 at index 1 Removing 34 at index 2 Removing 79 at index 3 Final array: [ 80, 56 ]
Key Points
-
Index adjustment: After using
splice(), decrement the index to avoid skipping elements -
Rest parameters: The
...valuessyntax allows passing multiple values to remove -
Array.from(): Converts the rest parameters into a proper array for
includes() - In-place modification: This method modifies the original array
Conclusion
Using includes() with splice() provides an effective way to remove multiple specific elements from an array. Remember to adjust the loop index after each removal to prevent skipping elements.
Advertisements
