JavaScript - Remove a specific element from an array JavaScript - Remove a specific element from an array

It's quite often that I have an array of elements and when a certain condition happens that I need to remove a particular element from my JavaScript array. Let's explore how indexOf and splice accomplish this.


Using splice to remove from an array

Removing an element from an array is a two part process:

  1. Find the element in the array
  2. Remove the element at the position found

Let's take a look at an example:


var myArray = [1,2,3,4,5];
var positionToRemove = myArray.indexOf(4);
if (positionToRemove > -1)
myArray.splice(positionToRemove, 1);

The key solution is using the JavaScript splice function. I am using it with two parameters. Parameter one is where we want to start removing from and parameter two is how many elements to remove. In our case, 1.

Published on Feb 7, 2019

Tags: JavaScript | splice | indexof

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.