splice() method changes the content of an array by removing or replacing existing elements and/or adding new elements. It takes three parameters:
To remove an element from the middle of an array, you first need to find the index of the element you want to remove. You can then pass that index into the
splice() method with a second parameter of 1 to indicate that you want to remove only one element from the array.
Here's an example:
let myArray = ['apple', 'banana', 'cherry', 'kiwi']; // Find the index of the element to remove let indexToRemove = 2; // Remove the element at the specified index myArray.splice(indexToRemove, 1); console.log(myArray); // Output: ["apple", "banana", "kiwi"]262 chars10 lines
In this example, we first define an array
myArray with four elements. We then find the index of the third element (which is
2 since array indices start at 0), and store it in a variable
We then call the
splice() method on
myArray with the parameters
1. This removes one element from the array starting at the
Finally, we log the updated
myArray to the console, which now contains only three elements without the one that we removed.