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:

[code]
var myArray = [1,2,3,4,5];

var positionToRemove = myArray.indexOf(4);
if (positionToRemove > -1)
myArray.splice(positionToRemove, 1);
[/code]

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.

Comments

Leave a Reply

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