There are several ways to remove the first element from an array.
The shift() method does not take any parameter.
// app.js let dark = ['Jonas', 'Martha', 'Mikkel', 'Ulrich', 'Adam', 'Eva'] removedEl = dark.shift(); console.log('Removed Element: ', removedEl); console.log('Remaining array', dark);
Removed Element: Jonas Remaining array [ 'Martha', 'Mikkel', 'Ulrich', 'Adam', 'Eva' ]
You can see that our first element is removed, Jonas, and then we printed the remaining array. The shift() method is faster than the splice() method, which we will see next.
Remove the first element using the array.splice()
array.splice(index, howmany, item1, ....., itemX)
The index parameter is required, and it is an integer that specifies at what position to add/remove items.
The howmany parameter is optional, and it is the number of items to be removed.
The item1, …, itemX parameters are optional, and it is the new item(s) to be added to the array.
The splice() method returns a new array containing the removed items.
// app.js let dark = ['Jonas', 'Martha', 'Mikkel', 'Ulrich', 'Adam', 'Eva'] removedEl = dark.splice(0, 1); console.log('Removed elements array: ', removedEl); console.log('Remaining array', dark);
Removed elements array: [ 'Jonas' ] Remaining array [ 'Martha', 'Mikkel', 'Ulrich', 'Adam', 'Eva' ]
You can see that the splice method does not return a single value; instead, it returns an array of removed items. It can be single or multiple elements of an array.
That’s it for this article.