How to Remove Elements from an Array
There are several ways to remove elements from existing arrays in JavaScript, as we demonstrate on this page. You can remove elements from the end of an array using pop
, from the beginning using shift
, or from the middle using splice
.
You can also remove elements from the end of an array by setting the length
property to a value less than the current value. Any element whose index is greater than or equal to the new length
will be removed:
var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); // [1, 2, 3, 4]
You can remove array elements using the delete
operator:
var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6
Using the delete
operator does not affect the length
property. Nor does it affect the indexes of subsequent elements. The array becomes sparse.[1] Compare with the splice
method described below.
How to Remove Elements from End of Array
The pop
method removes the last element of the array, returns that element, and updates the length
property. The pop
method modifies the array on which it is invoked.
var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]
How to Remove Elements from Beginning of Array
The shift
method works much like the pop
method except it removes the first element of the array instead of the last:
var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]
The shift
method returns the element that has been removed, updates the indexes of remaining elements, and updates the length
property. It modifies the array on which it is invoked.
How to Remove Elements from Middle of Array
The splice
method can be used to add or remove elements from an array. The first argument specifies the location at which to begin adding or removing elements. The second argument specifies the number of elements to remove. The third and subsequent arguments are optional; they specify elements to be added to the array.
Here we use the splice
method to remove two elements starting from position three:
var ar = [1, 2, 3, 'a', 'b', 'c'];
// arguments: start position, number of elements to delete
console.log( ar.splice(3, 2) ); // ["a", "b"]
console.log( ar ); // [1, 2, 3, "c"]
We use console.log
to display the value returned, which is an array containing the removed elements. Then we use console.log
to display the array after modification by our use of the splice
method.
- An array is said to be sparse when not all index values between zero and the array
length
are populated with array elements. ^