Removing an element from an Array in Javascript

JavascriptFront End TechnologyWeb Development

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"]
raja
Published on 06-Jul-2018 10:03:13
Advertisements