In this article we will learn how to remove element from beginning of an array in JavaScript.
It is very common to remove element from beginning of an array in JavaScript in JavaScript.
Problem
Now we have a problem, which is that we want to remove an element from the beginning of the array.
Imagine we have a array like that:
const array = [1, 2, 3, 4, 5];
And we want to remove an element from the beginning of this array.
Result will be like this
[2, 3, 4, 5]
How to solve this problem?
In fact, the solution to this problem is very easy, and there is more than one solution to this problem.
- Using
shift
method - Using
splice
method
Remove element from beginning using shift
We can use shift
method to remove an element from beginning of an array.
Let's see an example:
// Array
const array = [1, 2, 3, 4, 5];
// remove element from the beginning of an array
array.shift();
// Result:
console.log(array);
Output
[ 2, 3, 4, 5 ]
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. MDN
Remove element from beginning using splice
We can remove an element from beginning of an array using splice
method.
Let's see an example
// Array
const array = [1, 2, 3, 4, 5];
// remove element from the beginning of an array
const result = array.splice(1);
// Result:
console.log(result);
Output
[ 2, 3, 4, 5 ]
The splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it MDN
Thank you for reading
Thank you for reading my blog. 🚀