Array Delete Methods - shift(), pop(), splice() with Input field
Delete First Element
If you want to remove the first item from an array, you can use the shift() method.
This method removes the first element and shifts all remaining elements one position forward.
After running this, "anil" will be removed.
Delete Last Element
If you want to remove the last item, you can use the pop() method.
This will remove "john" from the array.
Delete Item from Any Position
If you want to delete an item from a specific position, you can use the splice() method.
Here, 2 is the index and 1 means delete one item. So "peter" will be removed.
You can also delete multiple items by changing the second value.
Delete Item Using Input Field
Now let’s make it more interesting. We will delete items based on user input.
When the user enters a position and clicks outside the input field, the item at that position will be deleted.
If the position is not valid, it will show an alert.
Important Things to Remember
Array index always starts from 0.
shift() removes the first element.
pop() removes the last element.
splice() is used to remove elements from any position.