Removing an element from an Array in Javascript


Let’s consider two cases while removing elements from an array. First, we will see how we can remove an element from the end of the array and in next section we will see how we can remove elements from the start of the array and from a given position of the element.

Removing an element from the end of the array

This can be accomplished using the pop method. For example,

let veggies = ["Onion", "Raddish"];
veggies.pop();
console.log(veggies);

This will give the output −

["Onion"]

Removing an element from the start of the array

This can be accomplished using the unshift method. For example,

let veggies = ["Onion", "Raddish"];
veggies.shift();
console.log(veggies);

This will give the output −

["Raddish"]

Removing an element from a given position of the array

Sometimes you need to remove an element from a given position in an array. JavaScript gives the splice method to remove from a given index. It can be used as follows −

let veggies = ["Onion", "Raddish", "Broccoli"];
veggies.splice(0, 1); // Removes 1 element from index 0
console.log(veggies);

This will give the output −

["Raddish", "Broccoli"]

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 15-Jun-2020

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements