The Array method shift() in Apps Script
The Array method shift()
removes the first element from an array and returns it.
Prerequisites
This tutorial assumes that you're familiar with:
Basic Apps Script concepts (such as Arrays in Apps Script).
How to create and run simple Apps Script scripts using the script editor in Google Sheets.
Syntaxarray.shift()
Parameters
array.shift()
Not applicable.
Return value
The shift()
method returns the first element from an array. If the array is empty, the shift()
method returns null
.
Example
The code below uses the shift()
array method to remove elements from the beginning of the array colors
.
🛈 Note
In Apps Script, you can only run functions. So you have to copy and paste the code snippet below into a function before you run it.
var colors = ["red", "blue"];
Logger.log(colors);
Logger.log(colors.length);
var color1 = colors.shift();
Logger.log(color1);
Logger.log(colors);
Logger.log(colors.length);
var color2 = colors.shift();
Logger.log(color2);
Logger.log(colors);
Logger.log(colors.length);
var color3 = colors.shift();
Logger.log(color3);
Logger.log(colors);
Logger.log(colors.length);
Output
[red, blue]
2.0
red
[blue]
1.0
blue
[]
0.0
null
[]
0.0
Conclusion
In this tutorial, you learned how to use the shift()
array method to remove elements from the beginning of an array.
Master Google Sheets Automation
I'd appreciate any feedback you can give me regarding this post.
Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!