JavaScript - Delete Element from the Beginning of JS Array
Last Updated :
14 Nov, 2024
Improve
These are the following ways to delete elements from JavaScript arrays:
1. Using shift() method - Mostly Used
The shift() method removes the first element from the array and adjusts its length.
const a = [1, 2, 3, 4];
// Remove the first element
a.shift();
console.log(a);
Output
[ 2, 3, 4 ]
2. Using splice() method
The splice() method is used to remove elements by specifying index and count.
const a = [1, 2, 3, 4];
// Remove the first element
a.splice(0, 1);
console.log(a);
Output
[ 2, 3, 4 ]
3. Using Destructuring Assignment
Array destructuring is used to extract the first element and create a new array with the rest elements.
const a1 = [1, 2, 3, 4];
// Skip the first element
const [, ...a2] = a1;
console.log(a2);
Output
[ 2, 3, 4 ]
4. Using Custom Method
The idea is to start from the second element and shift all the elements one position to the left. After shifting all the elements, reduce the array size by 1 to remove the extra element at the end.
const a = [1, 2, 3, 4];
for (let i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
// Adjust length to "delete" last element
a.length = a.length - 1;
console.log(a);
Output
[ 2, 3, 4 ]