Follow @endyourif rss Facebook LinkedIn

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

Published on Feb 7, 2019

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.

Tags: JavaScript | splice | indexof

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP