W3docs

How to Remove an Element from an Array in JavaScript

Read this tutorial and learn what several useful Array methods exist that will help you remove the specified element from an Array in JavaScript easily.

JavaScript suggests several methods to remove elements from existing Array. You can delete items from the end of an array using pop(), from the beginning using shift(), or from the middle using the <kbd class="highlighted">splice()</kbd> method. Let’s discuss them.

pop()

The <kbd class="highlighted">Array.prototype.pop()</kbd> method is used to remove the last element from the array and returns that element:

Javascript pop method removes the last element

javascript— editable

The <kbd class="highlighted">pop()</kbd> and <kbd class="highlighted">shift()</kbd> methods change the length of the array.

You can use the unshift() method to add a new element to an array.

splice()

The <kbd class="highlighted">Array.prototype.splice()</kbd> method is used to change the contents of an array by removing or replacing the existing items and/or adding new ones in place. The first argument defines the location at which to begin adding or removing elements. The second argument defines the number of elements to remove. The third and subsequent arguments are optional; they define elements to be added to the array.

At position 2 remove 1 item:

Javascript splice method changes array contents

javascript— editable

The <kbd class="highlighted">splice()</kbd> method coupled with indexOf() removes a specific element from an array. The <kbd class="highlighted">indexOf()</kbd> method searches for the element and returns its first index, or -1 if it is not present:

Javascript splice method with indexOf

javascript— editable

filter()

The filter() method creates a new array, unlike <kbd class="highlighted">splice()</kbd>. The method does not modify the array on which it is invoked, but returns a brand new array:

Javascript filter method creates a new array

javascript— editable

The delete Operator

This operator removes the element at the specified index (remember to start counting from zero).

Javascript delete operator

javascript— editable

The delete operator does not actually remove the element from the array; it creates an empty slot at that index, and the array length remains unchanged.