This content originally appeared on DEV Community and was authored by Dillion Megida
Article number 12 of the Array Method Series. In this article, I will explain the shift
Array method.
What is the Shift Method?
The shift
method of arrays shifts the first item out of an array.
This method returns the shifted item and also modifies the array--removing the item from the array.
Syntax of the Shift Method
array.shift()
Without the Shift Method
Here's how to imitate the shift
method:
let array = [1, 2, 3, 4, 5]
const shiftedValue = array[0]
const [, ...rest] = array
array = rest
console.log(shiftedValue)
// 1
console.log(array)
// [2, 3, 4, 5]
This approach is similar to what the shift
method does in the background. It returns the first item and removes it from the array, thereby making the array lesser in length by 1.
With the Shift Method
Here's how you achieve the previous result with shift
:
const array = [1, 2, 3, 4, 5]
const shiftedValue = array.shift()
console.log(shiftedValue)
// 1
console.log(array)
// [2, 3, 4, 5]
On the contrary to how shift
works, read on pop - for removing the last item from an array
This content originally appeared on DEV Community and was authored by Dillion Megida
Dillion Megida | Sciencx (2022-05-10T06:09:12+00:00) Array.shift() – for shifting the first item in an array. Retrieved from https://www.scien.cx/2022/05/10/array-shift-for-shifting-the-first-item-in-an-array/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.