4 Ways to remove an element from the array

Ways to remove an element from an array

JavaScript arrays allow you to group values and iterate over them. You can add and remove array elements in different ways. Unfortunately, there is not a simple Array.remove method. Here are some ways to remove an element from the array

  • pop
  • shift
  • splice
  • remove the specific element with splice

1. pop

The pop() method removes the last element of an array, and returns that element.

let fruits = ["🍓","🍊","🍇","🍎"];
fruits.pop();
console.log(fruits);

// [🍓,🍊,🍇]

2. shift

The shift() method removes the first item of an array. The shift() method changes the original array.

let fruits = ["🍓","🍊","🍇","🍎"];
fruits.shift();
console.log(fruits);

//[🍊,🍇,🍎]

3. splice

The splice() method adds/removes items to/from an array, and returns the removed item(s). Splice also changes the original array.

let fruits = ["🍓","🍊","🍇","🍎"];
fruits.splice(1,2);
console.log(fruits);

//[🍓,🍎]

4. Remove specific element with splice

let fruits = ["🍓","🍊","🍇","🍎"];
let applesPos = fruits.indexOf("🍎");
fruits.splice(applePos, 1);
console.log(fruits);

//[🍓,🍊,🍇]

Thanks for scrolling & Share this blog, if you have liked it. You can read our other blogs here.

Follow us on Instagram & GitHub. 💝

Other blog are:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × two =