There are various methods to remove the first element of an array in JavaScript.
1. Using shift() Method
The shift()
method removes the first element of an array. It modifies the original array by removing the first element and returns the removed element.
let arr = [10, 20, 30, 40, 50];
let item = arr.shift();
console.log(arr); // Output: [20, 30, 40, 50]
console.log(item); // Output: 10
2. Using slice() Method
The slice()
method creates a new array that excludes the first element. It does not modify the original array.
let arr = [10, 20, 30, 40, 50];
let newArr = arr.slice(1);
console.log(newArr); // Output: [20, 30, 40, 50]
console.log(arr); // Output: [10, 20, 30, 40, 50]
3. Using splice() Method
The splice()
method can be used to remove elements from an array by specifying the starting index and the number of elements to remove. This method modifies the original array.
let arr = [10, 20, 30, 40, 50];
let item = arr.splice(0, 1);
console.log(arr); // Output: [20, 30, 40, 50]
console.log(item); // Output: [10]
4. Using Destructuring Assignment
Destructuring can be used to extract the first element while keeping the rest of the array intact. This method creates a new array without modifying the original.
let arr = [10, 20, 30, 40, 50];
let [item, ...newArr] = arr;
console.log(newArr); // Output: [20, 30, 40, 50]
console.log(item); // Output: 10
5. Using filter() Method
The filter()
method can be used to create a new array by excluding the first element based on its index.
let arr = [10, 20, 30, 40, 50];
let newArr = arr.filter((_, index) => index !== 0);
console.log(newArr); // Output: [20, 30, 40, 50]
console.log(arr); // Output: [10, 20, 30, 40, 50]
6. Using a for Loop
For scenarios where you want full control, you can use a for
loop to manually shift elements to the left, effectively removing the first element.
let arr = [10, 20, 30, 40, 50];
let newArr = [];
for (let i = 1; i < arr.length; i++) {
newArr.push(arr[i]);
}
console.log(newArr); // Output: [20, 30, 40, 50]
7. Using Array.from() Method
You can use Array.from()
to create a new array starting from the second element.
let arr = [10, 20, 30, 40, 50];
let newArr = Array.from(arr.slice(1));
console.log(newArr); // Output: [20, 30, 40, 50]
console.log(arr); // Output: [10, 20, 30, 40, 50]