This article will show you how to remove first item from an array in JavaScript. There are several approaches to remove the first item from an array in JavaScript, each with a description and complete code example are given below:
1. Using Array.shift() Method
Using the shift()
method to remove and return the first item from an array.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; const removedItem = array.shift(); // Output: [ 'Orange', 'Grapes', 'Mango' ] console.log(removedItem); // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(array);
2. Using Array.slice() Method
Using the slice()
method to create a new array excluding the first item.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; const newArray = array.slice(1); // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
3. Using Array.splice() Method
Using the splice()
method to remove the first item by specifying the starting index and the number of items to remove.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; array.splice(0, 1); // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(array);
4. Using Array.slice() with Spread Operator
Using the slice()
method along with the spread operator to create a new array without the first item.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; const newArray = [...array.slice(1)]; // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
5. Using Array.filter() Method
Using the filter()
method to create a new array excluding the first item.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; const newArray = array.filter((_, index) => index > 0); // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
6. Using Array.slice() with for Loop
Using the slice()
method along with a for
loop to create a new array without the first item.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; const newArray = []; for (let i = 1; i < array.length; i++) { newArray.push(array[i]); } // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
7. Using Array.slice() with Destructuring
Using slice()
along with array destructuring to create a new array without the first item.
const array = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; const [, ...newArray] = array; // Output: [ 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);