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:

Javascript shift method remove the sgift element
let myArray = ["1", "2", "3", "4"]; console.log(myArray.shift());

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:

Javascript splice method change the contents of an array
let myArray = ['a', 'b', 'c', 'd']; console.log(myArray.splice(2, 1));

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:

Javascript splice method change the contents of an array
let myArray = ["a", "b", "c", "d"]; console.log(myArray.splice (myArray.indexOf('c'), 2));

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:

Javascript filter method creates a new array
function isEven(value) { return value%2 == 0; } arr = [13, 8, 15, 31, 44]; function func() { console.log(arr.filter(isEven)); } func();

The delete Operator

This operator will delete the element which is specified in the index (remember to start counting from zero).

Javascript splice method
let myArray = ["1", "2", "3", "4"]; delete myArray[2]; console.log(myArray); // Output: [ "1", "2", null, "4" ]

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.