How To Remove the First 2 Elements from an Array using JavaScript

How To Remove the First 2 Elements from an Array using JavaScript

To remove the first 2 elements from an array using JavaScript, we have two effective methods: Creating the function to remove the first 2 elements using the filter() method or using the splice() method. Check out the details below to get more information.

Remove the first 2 elements from an array using JavaScript

Create the function to remove the first 2 elements using the filter() method

To remove the first 2 elements from an array in Javascript, we can easily create the function to do that using the filter() method. To get more information about the filter() method. Please read the other article of us here.

Example: 

In this example, we will create a myArray array with five elements. Then create the function removeFirst2Element() to remove two elements at the beginning of myArray. After that, we will call the function removeFirst2Element() with the filter() method to remove the first two elements. 

var myArray = [1, 2, 3, 4, 5];

// Create the function to return the array without the first and second element in 'myArray'
function removeFirst2Element(element, index) {
  	return index !== 0 & index !== 1;
}

console.log("My array is : ", myArray);
var newArray = myArray.filter(removeFirst2Element); // [3, 4, 5]
console.log("After removing the first two elements in myArray:", newArray);

Output

My array is : [1, 2, 3, 4, 5]
After removing the first two elements in myArray: [3, 4, 5]

Use the splice() method

The other simple way to remove the first two elements from an array is use the splice() method.

Syntax:

array.splice(index, howmany, item1, ..., itemX)

Parameters: 

  • index: The position to add/remove items.
  • howmany: Number of items to be removed.
  • item1, …, itemX: New elements to be added.

Return value: An array containing the removed items.

Example:

var myArray = [1, 2, 3, 4, 5];
console.log("My array is : ", myArray);

// Use splice() method with index to remove is 0 and number to remove is 2
myArray.splice(0, 2);

console.log("After removing the first 2 element in myArray: ", myArray);

Output

My array is : [1, 2, 3, 4, 5]
After removing the first 2 elements in myArray: [3, 4, 5]

Summary

In this tutorial, we have explained how to remove the first 2 elements from an array using JavaScript. We always hope this tutorial is helpful to you. Leave your comment here if you have questions or comments about improving the article.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *