Home Courses Array Delete Methods - shift(), pop(), splice() with Input field

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.


let users = ["anil", "sam", "peter", "bruce", "john"];

users.shift();
console.log(users);

After running this, "anil" will be removed.


Delete Last Element

If you want to remove the last item, you can use the pop() method.


let users = ["anil", "sam", "peter", "bruce", "john"];

users.pop();
console.log(users);

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.


let users = ["anil", "sam", "peter", "bruce", "john"];

users.splice(2, 1);
console.log(users);

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.


<html>
<head></head>
<body>
<h1>Delete Array Item in JavaScript</h1>
<span>Delete Array Element</span>
<input type="text" onblur="deleteItem(event)" placeholder="enter position">

<script>
let users = ["anil", "sam", "peter", "bruce", "john"];
console.log(users);

function deleteItem(event) {
let pos = event.target.value;

if (pos > users.length - 1) {
alert("Position not valid");
} else {
users.splice(pos, 1);
console.log(users);
}
}
</script>
</body>
</html>

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.

Share this lesson: