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