How to remove a specific JavaScript array element? Splice, delete functions

The methods for removing array elements

The JavaScript provides a few methods for removing array elements. These include pop and shift methods.

The pop method removes the first element from the given array.

The shift method removes the last element from the given array.

You may set the length of an array as 0 if require removing all the elements from the given array.

However, what if you need to remove a specific element from an array?

For example:

Or

You may use the array splice method for removing a specific element from the given array. The array splice returns a new array of removed elements. While the specified array in the splice method contains the remaining elements after removing the specified elements.

See the demos below for learning to use the splice JavaScript method and other ways for removing particular elements.

A demo of removing the specific element using splice method

In this demo, an array of numbers is created. Five elements are added in the array initially. After that, the array splice method is used for removing the third element by zero-based index number.

The numeric array elements are displayed before and after using the JavaScript splice method as follows:

javascript splice

See online demo and code

The JS code with splice:

 

You noticed I used two parameters in the splice method. The first specifies the index of the element to be removed. The second parameter tells how many elements to remove after the specified index.

See the demo below if you leave the second parameter.

What if the second parameter is not provided in array splice JS method?

Using the same code as in above example except the second parameter is not given in the splice method i.e.:

Arr_Numbers.splice(2);

See the code and output:

javascript splice no parameter

See online demo and code

You can see, it removed all elements ahead of the given index number as well.

In addition, I also displayed the removed array elements, as such, the splice method returns an array of removed elements.

The JS code:

 

Using the delete function for removing array element

You may also use the delete function for removing a specific element in an array. However, the delete function keeps an empty spot and if you iterate through that array after using the delete function, it will display that specific element as undefined.

Have a look at this demo using the delete function:

javascript array delete

See online demo and code

The JavaScript code for using the delete function:

 

You can see, the undefined is displayed for the third element after it is removed by using the delete function.

Note: You have to provide index number in square brackets as using the delete.

It is recommended to use splice method for arrays. The delete may complicate the situation as undefined spots are created.