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 elements using the splice() method in JavaScript?
The splice() method is used to remove elements from an array by specifying the starting index and the number of elements to delete. It modifies the original array and returns an array of the removed elements.
Syntax
array.splice(startIndex, deleteCount)
Parameters
- startIndex: The index at which to start removing elements
- deleteCount: The number of elements to remove
Example: Remove Single Element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Splice Method Example</title>
</head>
<body>
<h1>Remove Elements using splice()</h1>
<div id="original"></div>
<div id="result"></div>
<button id="removeBtn">Remove Elements</button>
<script>
let arr = [1, 3, 5, 7, 9, 11];
document.getElementById('original').innerHTML = 'Original array: [' + arr + ']';
document.getElementById('removeBtn').addEventListener('click', () => {
let removed = arr.splice(1, 4); // Remove 4 elements starting from index 1
document.getElementById('result').innerHTML = 'After splice: [' + arr + ']<br>Removed elements: [' + removed + ']';
});
</script>
</body>
</html>
Output
Initially displays: Original array: [1, 3, 5, 7, 9, 11]
After clicking the button: After splice: [1, 11] and Removed elements: [3, 5, 7, 9]
Different splice() Scenarios
<!DOCTYPE html>
<html>
<head>
<title>Splice Examples</title>
</head>
<body>
<div id="examples"></div>
<script>
let output = '';
// Remove from beginning
let arr1 = ['a', 'b', 'c', 'd', 'e'];
let removed1 = arr1.splice(0, 2);
output += 'Remove first 2: [' + arr1 + '], Removed: [' + removed1 + ']<br>';
// Remove from end
let arr2 = ['a', 'b', 'c', 'd', 'e'];
let removed2 = arr2.splice(-2, 2);
output += 'Remove last 2: [' + arr2 + '], Removed: [' + removed2 + ']<br>';
// Remove single element
let arr3 = ['a', 'b', 'c', 'd', 'e'];
let removed3 = arr3.splice(2, 1);
output += 'Remove index 2: [' + arr3 + '], Removed: [' + removed3 + ']<br>';
document.getElementById('examples').innerHTML = output;
</script>
</body>
</html>
Output
Remove first 2: [c,d,e], Removed: [a,b] Remove last 2: [a,b,c], Removed: [d,e] Remove index 2: [a,b,d,e], Removed: [c]
Key Points
-
splice()modifies the original array - Returns an array of removed elements
- Negative indices count from the end of the array
- If deleteCount is omitted, all elements from startIndex to the end are removed
Conclusion
The splice() method provides a powerful way to remove elements from arrays. It's particularly useful when you need to know which elements were removed or when removing multiple consecutive elements.
Advertisements
