How to Remove an Element from an Array in JavaScript
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 splice() functions. Let’s discuss them.
pop()
The Array.prototype.shift() method is used to remove the last element from the array and returns that element:
The pop() and shift() methods change the length of the array.
You can use unshift() method to add a new element to an array.
splice()
The Array.prototype.splice() 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:
The splice() coupled with indexOf() removes the item or items from an array. The indexOf() searches and removes a specific element. The method will return the first index at which the specified element can be found in the array, or -1 if it is not present:
filter()
The filter() method creates a new array, unlike splice(). The method does not modify the array on which it is invoked, but returns a brand new array:
The delete Operator
This operator will delete the element which is specified in the index (remember to start counting from zero).
The delete operator actually does not delete the element from the array it just frees the memory. The memory is freed if there are no more references to that value.