Remove Element from Array at any Index using splice() Method
Splice method is used to modify the contents of an array by removing the existing elements and/or adding new elements. To remove elements by the splice() method you can specify the elements in different ways.
Example 1: This example uses the indexing of the splice method to remove elements from a JavaScript array.
// JavaScript code to illustrate splice() function
let arr = ["shift", "splice", "filter", "pop"];
// Removing the specified element from the array
let spliced = arr.splice(1, 1);
console.log("Removed element: " + spliced);
console.log("Remaining elements: " + arr);
Output
Removed element: splice Remaining elements: shift,filter,pop
Example 2: This example uses the value of the splice method to remove elements from a JavaScript array.
// JavaScript code to illustrate splice() function
let arr = ["shift", "splice", "filter", "pop"];
// Removing the specified element by value from the array
for (let i = 0; i < arr.length; i++) {
if (arr[i] === "splice") {
let spliced = arr.splice(i, 1);
console.log("Removed element: " + spliced);
console.log("Remaining elements: " + arr);
}
}
Output
Removed element: splice Remaining elements: shift,filter,pop
Example 3: Using the splice method to remove each element from a JavaScript array.
// Declare and initialize array
let array = ["pop", "splice", "filter", "shift"]
console.log("Original array: " + array)
// Making the length of array to 0 by using splice method
array.splice(0, array.length);
console.log("Empty array: " + array)
Output
Original array: pop,splice,filter,shift Empty array:
Remove elements from a JavaScript Array
Removing elements from a JavaScript array means taking out certain items from the array. This is a basic and important task in programming because it helps keep the array accurate and makes data handling easier. In this article, we will discuss few methods to remove elements from a JavaScript Array.